【发布时间】:2014-04-15 21:10:20
【问题描述】:
我有以下模型:RECIPE、TAG 和 TAGGING(连接表)
食谱.rb
has_many :taggings
has_many :tags, through: :taggings
accepts_nested_attributes_for :taggings
标签.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
当我创建一个新配方时,标签通常会添加到连接表(标签)中。但是当我编辑 collection_select 帮助器时,并没有将项目标记为“已选择”。
如何构造多范围的collection_select?
如何为 EDIT/UPDATE 操作构造 collection_select?
还有其他更好的方法吗?
【问题讨论】:
标签: sql ruby-on-rails ruby-on-rails-4 many-to-many has-many-through