我有两个模特:
品牌
has_many :products积
belongs_to :brand在我看来,(show_brand.html.erb),使用@brand.name ...显示关于品牌的所有信息。
我想为产品创建表单,belongs_to 品牌显示有关信息。
类似于:
form_for(@brand.products) ...user_id附加到product form (product belongs_to user)而无需在控制器中添加它注意:关于我列表中的第一项,我知道可以通过将路由升级到嵌套的数组和传递带有main对象和关联对象的数组来完成。但如果有其他方法可以做到的话?而不修改routes.rb和..。
发布于 2015-06-17 05:04:25
您可以使用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 %>发布于 2015-06-17 00:37:44
对于问题1,您可以使用“嵌套表单”。请检查下面的链接。http://railscasts.com/episodes/196-nested-model-form-part-1?view=asciicast
对于第二个问题,即使您将user_id设置为"product“,您仍然必须在控制器/模型中进行一些检查,以防将任何不想要的值设置为user_id。所以更好的方法是你自己把它设置在后端。
https://stackoverflow.com/questions/30880285
复制相似问题