我有两个模型:
品牌
has_many :products
产品
belongs_to :brand
在我看来 (show_brand.html.erb),我使用 @brand.name ...
显示有关品牌的所有信息。
我想为属于品牌的产品创建表单,我正在显示相关信息。
类似于:
form_for(@brand.products) ...
- 我该如何执行?
- 如何将
user_id
附加到 product 表单(productbelongs_to
user ) 而无需手动将其添加到 Controller 中
注意: 关于我列表中的第一项,我知道可以通过将路由升级为嵌套并传递带有主对象和关联对象的数组来完成。但如果有另一种方法呢?不修改 routes.rb 和 ...
最佳答案
您可以使用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 %>
关于ruby-on-rails - 为模型关联创建 form_for,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30880285/