0
我有这样的:两个collection_select将它保存为两个不同的记录
<%= f.collection_select :category_ids, Category.all, :id, :name, {} %>
我的表单中,它创造的纪录没问题,但我失去了对如何使内部的相同更加两个或两个以上的记录形式,我尝试的所有事情要么创建一个记录,要么根本不创建。我发现这个解决方案,我分析,肯定是要去工作(altough我真的不明白为什么它采用无):
<%= f.fields_for :category_ids do |category| %>
<%= category.collection_select(nil, Category.all, :id, :name,
{include_blank: "---", selected: 0},
{id: :event_category_id_1}) %>
<%= category.collection_select(nil, Category.all, :id, :name,
{include_blank: "---", selected: 0},
{id: :event_category_id_2}) %>
<% end %>
但这次它创建没有记录的。
这里是我的模型:
class Event < ApplicationRecord
has_many :categorizations
has_many :categories, through: :categorizations
accepts_nested_attributes_for :categorizations
end
class Category < ApplicationRecord
has_many :categorizations
has_many :events, through: :categorizations
end
class Categorization < ApplicationRecord
belongs_to :event
belongs_to :category
end
您当然可以改进UI,将选定的类别复制到选择标记下方的列表中,类似的东西。 –
我已经看到你可以使用multiple:选项,但是我认为用户选择多个有点难,是否有一种方法可以创建两个collection_select(甚至是一个简单的选择),以便在同样的形式? – Bluespheal
啊,你有'has_many through',你的fields_for需要用于':categorizations'。阅读在thoughtbot如何做到这些https://robots.thoughtbot.com/accepts-nested-attributes-for-with-has-many-through –