I have a tag system that uses has_many: through relationships. None of the solutions here led me to where I needed to go, so I came up with a solution that could help others. This has been tested on Rails 3.2.
Customization
Here is the basic version of my models:
Location Object:
class Location < ActiveRecord::Base has_many :city_taggables, :as => :city_taggable, :dependent => :destroy has_many :city_tags, :through => :city_taggables accepts_nested_attributes_for :city_tags, :reject_if => :all_blank, allow_destroy: true end
Tag objects
class CityTaggable < ActiveRecord::Base belongs_to :city_tag belongs_to :city_taggable, :polymorphic => true end class CityTag < ActiveRecord::Base has_many :city_taggables, :dependent => :destroy has_many :ads, :through => :city_taggables end
Decision
I really redefined the autosave_associated_record_for method as follows:
class Location < ActiveRecord::Base private def autosave_associated_records_for_city_tags tags =[]
The above implementation saves, deletes and modifies tags as I needed, using the fields for the nested form. I am open to feedback if there are ways to simplify. It is important to note that I explicitly change tags when the label changes, rather than updating the tag label.
source share