Reputation: 5482
I have 2 models:
brand
has_many :products
product
belongs_to :brand
In my view (show_brand.html.erb), i displaying all information about brand using @brand.name ...
.
I want to create form for product that belongs_to brand i'm displaying information about.
Something like:
form_for(@brand.products) ...
user_id
to product form (product belongs_to
user) without adding it in controller manuallyNOTICE: About first item in my list, i know that it can be done by upgrading routes to nested and passing array with main object and association object. But if there is another way of doing that? Without modifying routes.rb and ...
Upvotes: 3
Views: 8249
Reputation: 33542
You can use accepts_nested_attributes_for
.
#brand_controller.rb
def new
@brand = Brand.new
@product = @brand.products.build
end
def create
@brand = Brand.new(brand_params)
if @brand.save
.....
else
.....
end
end
private
def brand_params
params.require(:brand).permit(:id, brand_attribute_1, brand_attribute_2, products_attributes: [:id, :product_attribute_1, :user_id, :product_attribute_2])
end
In your form
<%= form_for @brand do |f| %>
----code for brand attributes ---
<%= f.fields_for @product do |p| %>
----code for product attributes----
<%= p.hidden_field user_id, :value => current_user.id %> #to attach user_id to product
<% end %>
<%= f.submit "Submit" %>
<% end %>
Upvotes: 2
Reputation: 373
For question 1, you can use "nested form". Please check below link. http://railscasts.com/episodes/196-nested-model-form-part-1?view=asciicast
For question 2, even though you set user_id in "product form", you still have to do some check in your controller/model in case any undesired value is set to user_id. So the better way is you set it yourself at backend.
Upvotes: 1