【问题标题】:Populate the select tag with models that another model belongs to使用另一个模型所属的模型填充选择标签
【发布时间】:2016-11-04 17:16:34
【问题描述】:

我有两个模型 - ProductProductCategoryProduct属于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 我查看了文档,问题是我需要一些相反的东西——我有一个属于ProductCategoryProduct

标签: ruby-on-rails ruby


【解决方案1】:

试试这个:

product_category_ids 不是product 模型的列

<%= form_for @product do |f| %>
    <%= f.collection_select :product_category_id, ProductCategory.all, :id, :name, 
                                                          {multiple: true} %>
<% end %>

【讨论】:

  • 没有错误,它只是返回一个空的select 标签。虽然在我的服务器日志中我可以看到一个请求 SELECT "product_categories".* FROM "product_categories"
  • ProductCategory表有数据吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多