options_for_select 没有选择类别

options_for_select doesn't choose a category

我想 select 分类 form_for

f.select :category_id, options_for_select(Category.select(:title, :id).map{|cat|[cat.title, cat.id]})

但每次我在对象中检查 category_id 时,都等于 nil。 有人可以帮助我吗,我哪里出错了?

求解! 我在 params.required..

中忘记了 category_id

您可以使用 .pluck 而不是 .select,这会立即为您提供一个元组数组:

[[1, "A title"], [2, "Another title"]]

f.select(:category_id, Category.pluck(:id, :title))

Rails 也 has convenient helpers 用于处理集合:

f.collection_select(:category_id, Category.all, :id, :title)