简体   繁体   中英

Creating form_for for model association

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) ...
  1. How can i preform that?
  2. How can i attach user_id to product form ( product belongs_to user ) without adding it in controller manually

NOTICE: 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 ...

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 %>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM