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'%>
has_many :products, :dependent => :destroy
resources :brands do resources :products end
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,
@brand = Brand.find(params[:brand_id]) @product = Product.new
form_for [@brand, @product] do |f|