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?
Try with
Instead of
Because you are returning new tagging everytime instead of re-using the previously created ones.
It worked for me: