使用 has_many 创建和更新:通过 Rails
Creating and Updating with has_many: through in Rails
我在 Rails 4 中分配 has_many: through
遇到了很多麻烦。
我有一个正常工作的 has_many: through
,table products
和 programs
加入了 table program_products
。我的模型运行正常,因为 Product.programs = Program.all
成功地将 programs
分配给了我的 products
。但是,我不知道如何在视图中获得该功能。
我了解到最常见的方法是使用 collection_check_boxes
,因此我在表单视图中设计了以下内容:
<%= form_for(@product) do |f| %>
<%= f.collection_check_boxes(:programs, Program.all, :id, :name ) %>
<%= f.submit %>
<% end %>
这给了我
的 HTML 输出
<input type="checkbox" value="1" name="product[programs][]" id="product_programs_1">
<input type="checkbox" value="2" name="product[programs][]" id="product_programs_2">
等等。
当我提交我的表单时,我在参数中得到了这个回复:
{"utf8"=>"✓",
"_method"=>"patch",
"authenticity_token"=>"xxx",
"product"=>{"name"=>"Test",
"description"=>"desc test",
"price"=>"10",
"programs"=>["1",
"2",
"3",
""]},
"commit"=>"Update Product",
"id"=>"18"}
没有错误。但是,我的数据库实际上从未更新过,所以我不知道出了什么问题。以下是我的控制器的重要部分:
products_controller.rb(主要 CRUD 控制器)
def update
@product = Product.find(params[:id])
if @product.update_attributes(product_params)
redirect_to(pages_dashboard_path)
end
end
private
def product_params
params.require(:product).permit(:name, :description, :price, :programs)
end
我不知道出了什么问题,因为我没有收到任何彻底的错误。 Rails 上 collection_check_boxes 的文档相当混乱,因此我怀疑我的错误可能在于该设置。
谢谢
我认为您应该在 collection_check_boxes
调用中使用 program_ids
而不是 programs
。并确保在许可方法中也进行更改。
我在 Rails 4 中分配 has_many: through
遇到了很多麻烦。
我有一个正常工作的 has_many: through
,table products
和 programs
加入了 table program_products
。我的模型运行正常,因为 Product.programs = Program.all
成功地将 programs
分配给了我的 products
。但是,我不知道如何在视图中获得该功能。
我了解到最常见的方法是使用 collection_check_boxes
,因此我在表单视图中设计了以下内容:
<%= form_for(@product) do |f| %>
<%= f.collection_check_boxes(:programs, Program.all, :id, :name ) %>
<%= f.submit %>
<% end %>
这给了我
的 HTML 输出<input type="checkbox" value="1" name="product[programs][]" id="product_programs_1">
<input type="checkbox" value="2" name="product[programs][]" id="product_programs_2">
等等。
当我提交我的表单时,我在参数中得到了这个回复:
{"utf8"=>"✓",
"_method"=>"patch",
"authenticity_token"=>"xxx",
"product"=>{"name"=>"Test",
"description"=>"desc test",
"price"=>"10",
"programs"=>["1",
"2",
"3",
""]},
"commit"=>"Update Product",
"id"=>"18"}
没有错误。但是,我的数据库实际上从未更新过,所以我不知道出了什么问题。以下是我的控制器的重要部分:
products_controller.rb(主要 CRUD 控制器)
def update
@product = Product.find(params[:id])
if @product.update_attributes(product_params)
redirect_to(pages_dashboard_path)
end
end
private
def product_params
params.require(:product).permit(:name, :description, :price, :programs)
end
我不知道出了什么问题,因为我没有收到任何彻底的错误。 Rails 上 collection_check_boxes 的文档相当混乱,因此我怀疑我的错误可能在于该设置。
谢谢
我认为您应该在 collection_check_boxes
调用中使用 program_ids
而不是 programs
。并确保在许可方法中也进行更改。