通过模型</select>为belongs_to渲染一个`<select>`

时间:2014-09-08 07:03:37

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

我想为belongs_to through model创建一个<select>输入。

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>

1 个答案:

答案 0 :(得分:0)

未选择属于关联,因为您的Post模型没有列tag_id,因此错误。您可以使用简单的select_tag来呈现此选择:

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