【问题标题】:Render a `<select>` for a belongs_to through model通过模型为 belongs_to 渲染一个`<select>`
【发布时间】:2014-11-01 08:36:11
【问题描述】:

我想通过模型为 belongs_to 创建一个&lt;select&gt; 输入。

一个post has_many tags,通过post_tags

这里有一些模型可以帮助你描绘它:

posts
  has_many :post_tags
  has_many :tags, through: :post_tags

post_tags
  belongs_to :post
  belongs_to :tag

tags
  has_many :post_tags
  has_many :posts, through: :post_tags

在我的新帖子表单中,我想要一个包含所有可能标签的选择下拉菜单。所以它应该是 Tag.all ,每个标签都有一个选项。我该如何渲染这个?

这是我尝试过的:

<%= collection_select("post", "tag_id", Tag.all, :id, :name) %>

Error: undefined method `tag_id' for #<Post:0x007ffd464a62d0>

【问题讨论】:

  • 请发布您的模型
  • 请同时发布带有视图的整个错误
  • 您在寻找什么?那是呈现错误的 html,这就是整个错误。您知道仅给出这些模型的 collection_select 的标准语法吗?
  • 语法不是问题这里问题是collection_select中的tag_id apidock.com/rails/ActionView/Helpers/FormOptionsHelper/…
  • 类似&lt;%= f.collection_select "tag_ids", Tag.all, :id, :name %&gt;

标签: ruby-on-rails ruby-on-rails-4 actionview


【解决方案1】:

这不是为属于 assication 选择的,因为您的 Post 模型没有列 tag_id,所以这是错误的。您可以使用简单的select_tag 来呈现此选择:

<%= select_tag "post[tag_id]", options_from_collection_for_select(Tag.all, 'id', 'name') %>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-06
    • 1970-01-01
    相关资源
    最近更新 更多