问题描述:

I'm working in Ruby on Rails, I have a products and brands, and when I'm in a Brand I want to create a new product that belongs to that brand, then I want to link_to with the brand_id.

How can I do that?

<%= link_to 'New Product', new_product_path, :class => 'btn btn-primary'%>

brand model

has_many :products, :dependent => :destroy

product model

 belongs_to :brand

网友答案:

The routes:

resources :brands do
    resources :products
end

The link:

link_to "New product", new_brand_product_path(@brand), class: "btn"

If you can create products outside of a brand, you might want to use a scope in your routes:

resources :brands do
    scope module: "brand_scope" do
        resources :products
    end
end

This way, you can have a separate controller to create products within a brand: app/controllers/brand_scope/products_controller.rb, but the path (new_brand_product_path(@brand)) is still the same.


In products controller, new action:

@brand = Brand.find(params[:brand_id])
@product = Product.new

In views/brand_scope/products/_new.html.erb:

form_for [@brand, @product] do |f|
相关阅读:
Top