通过具有多次关联的关系来编辑/更新collection_select [英] edit/update collection_select with has-many-through association
问题描述
我有以下模型:RECIPE,TAG和TAGGING(联接表)
I have the following models: RECIPE, TAG and TAGGING (join table)
recipe.rb
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"的字段,这为我的标签带来了一种分类.因此,我创建了一些范围"以区分彼此.
Everything normal so far. But, in my TAGS table I have a field called "type_id" which brings me a kind of categorization of my tags. So I've created some "scopes" to distinguish each other.
tagging.rb
tagging.rb
belongs_to :recipe
belongs_to :tag, :counter_cache => :recipes_count
recipes_controller.rb
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
当我创建NEW RECIPE时,标记通常添加到联接表(标记)中.但是,当我编辑collection_select助手时,不会将该项目标记为已选中".
When I create a NEW RECIPE the tags are added in join table (taggings) normally. But when I edit the collection_select helper does not mark as "selected" the item.
如何构造具有多个作用域的collection_select?
如何构造用于edit/update动作的collection_select?
还有另一种更好的方法吗?
推荐答案
它对我有用:
= 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
这篇关于通过具有多次关联的关系来编辑/更新collection_select的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!