【发布时间】:2016-11-04 17:16:34
【问题描述】:
我有两个模型 - Product 和 ProductCategory。 Product属于ProductCategory,产品类别也可以有很多产品。现在我正在尝试在表单中创建一个选择标签以创建一个新的Product,我将在其中选择一个类别并将这个新产品设置为属于该类别,但我很困惑如何做到这一点。在我的控制器中,我有
def create
@product = Product.new(product_params)
@product.save
redirect_to products_path
end
private
def product_params
params.require(:product).permit(:name, :description, :price, :product_category_id)
end
在我看来,我试图做这样的事情:
<%= form_for @product do |f| %>
<%= f.collection_select :product_category_ids, ProductCategory.all, :id, :name,
{multiple: true} %>
<% end %>
但是我遇到了以下错误
undefined method `product_category_ids' for #<Product:0x007f4982afa758>
我应该如何使这个选择标签起作用?
添加
我也试过这样制作:
<%= f.select :product_category_id, ProductCategory.all.collect { |c| [c.name, c.id] }, include_blank: true %>
但它返回给我的只是一个空的option 标签。
【问题讨论】:
-
您应该使用
nested_form创建属于某个产品类别的产品。欲了解更多详情,请访问github.com/ryanb/nested_form -
@Udaykumardas 我查看了文档,问题是我需要一些相反的东西——我有一个属于
ProductCategory的Product
标签: ruby-on-rails ruby