为模型关联创建form_for

时间:2015-06-17 00:08:40

标签: ruby-on-rails associations form-for

我有2个型号:

品牌

has_many :products

产品

belongs_to :brand

在我看来( show_brand.html.erb ),我使用@brand.name ...显示有关品牌的所有信息。

我想创建产品的表单,即品牌我显示的信息。

类似的东西:

form_for(@brand.products) ...
  1. 我如何预先形成?
  2. 如何将user_id附加到产品表单(产品 belongs_to 用户)而不将其添加到控制器中手动
  3. 注意:   关于我列表中的第一项,我知道可以通过将路由升级到嵌套并使用主对象和关联对象传递数组来完成。但是,如果还有另一种方法吗?无需修改 routes.rb 和...

2 个答案:

答案 0 :(得分:1)

对于问题1,您可以使用“嵌套表单”。 请查看以下链接。 http://railscasts.com/episodes/196-nested-model-form-part-1?view=asciicast

对于问题2,即使您在“产品表单”中设置了user_id,仍然需要对控制器/模型进行一些检查,以防将任何不需要的值设置为user_id。所以更好的方法是你自己在后端设置它。

答案 1 :(得分:1)

您可以使用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

以您的形式

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