我有以下型号:RECIPE,TAG和TAGGING(连接表)
recipe.rb
has_many :taggings
has_many :tags, through: :taggings
accepts_nested_attributes_for :taggings
tag.rb
has_many :taggings
has_many :recipes, through: :taggings
scope :diet, -> { where(type_id: 1).to_a }
scope :category, -> { where(type_id: 2).to_a }
scope :festivity, -> { where(type_id: 3).to_a }
scope :daily, -> { where(type_id: 4).to_a }
到目前为止一切正常。但是,在我的TAGS表中,我有一个名为“type_id”的字段,它带给我一种我的标签分类。所以我创造了一些“范围”来区分彼此。
tagging.rb
belongs_to :recipe
belongs_to :tag, :counter_cache => :recipes_count
recipes_controller.rb
def new
@recipe = Recipe.new
@recipe.tags.build
@recipe.taggings.build(:recipe => @recipe)
end
def edit
end
我的表格
= f.fields_for :taggings, @recipe.taggings.build do |builder|
= builder.collection_select :tag_id, Tag.diet, :id, :name
= f.fields_for :taggings, @recipe.taggings.build do |builder|
= builder.collection_select :tag_id, Tag.category, :id, :name
= f.fields_for :taggings, @recipe.taggings.build do |builder|
= builder.collection_select :tag_id, Tag.festivity, :id, :name
= f.fields_for :taggings, @recipe.taggings.build do |builder|
= builder.collection_select :tag_id, Tag.daily, :id, :name
当我创建新的RECIPE时,标签通常会添加到连接表(标签)中。但是当我编辑collection_select时,帮助器没有标记为“选中”该项目。
如何构建包含多个范围的collection_select?
如何为EDIT / UPDATE操作构建collection_select?
还有其他更好的方法吗?
答案 0 :(得分:1)
尝试
= f.fields_for :taggings, @recipe.taggings do |builder|
而不是
= f.fields_for :taggings, @recipe.taggings.build do |builder|
因为您每次都返回新的标记,而不是重新使用以前创建的标记。
答案 1 :(得分:0)
它对我有用:
= f.fields_for :taggings, @recipe.taggings.order("id").first do |diet|
= diet.collection_select :tag_id, Tag.diet, :id, :name
= f.fields_for :taggings, @recipe.taggings.order("id").second do |category|
= category.collection_select :tag_id, Tag.category, :id, :name
= f.fields_for :taggings, @recipe.taggings.order("id").third do |festivity|
= festivity.collection_select :tag_id, Tag.festivity, :id, :name
= f.fields_for :taggings, @recipe.taggings.order("id").fourth do |daily|
= daily.collection_select :tag_id, Tag.daily, :id, :name