edit/update collection_select with has-many-through association

时光怂恿深爱的人放手 提交于 2019-12-12 00:47:37

问题


I have the following models: RECIPE, TAG and TAGGING (join table)

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 }

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

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

my form

= 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

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.

How to construct the collection_select with many scopes?

How to construct the collection_select for EDIT/UPDATE actions?

Is there another better way to do that?


回答1:


Try with

= f.fields_for :taggings, @recipe.taggings do |builder| 

Instead of

= f.fields_for :taggings, @recipe.taggings.build do |builder| 

Because you are returning new tagging everytime instead of re-using the previously created ones.




回答2:


It worked for me:

= 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


来源:https://stackoverflow.com/questions/22339571/edit-update-collection-select-with-has-many-through-association

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!