activerecord - Rails 3 - Owning and "tracking" the same object type using has_many and has_many as:trackable (polymorphic) -


in project need user able both "create/own" own objects , "track" (or "follow") objects created other users. here approach:

class user < activerecord::base has_many :widgets has_many :gadgets has_many :nuggets has_many :tracks has_many :tracked_widgets, :as => :trackable, :trackable_type => "widget" has_many :tracked_gadgets, :as => :trackable, :trackable_type => "gadget" has_many :tracked_nuggets, :as => :trackable, :trackable_type => "nugget" end class track < activerecord::base belongs_to :trackable, polymorphic: true belongs_to :user end class widget < activerecord::base # gadget , nugget classes same has_many :tracks, :as => :trackable end 

the schema tracks table:

 create_table "tracks", :force => true |t| t.integer "user_id" t.integer "trackable_id" t.string "trackable_type" t.datetime "created_at" t.datetime "updated_at" end add_index "tracks", ["trackable_id", "user_id"], :name => "index_tracks_on_trackable_id_and_user_id" 

with implementation following error:

unknown key: trackable_type (argumenterror) 

looking @ schema, it's obvious don't have :trackable_type set index, error message makes sense. however, in examples i've seen demonstrate polymorphic relationships, i've never seen ______able_type field set index. makes me wonder if i'm missing basic here. have these questions:

  1. have somehow incorrectly set has_many , :as => :trackable relationships?
  2. if not, there issue using string field index?
  3. if answer add :trackable_type field index, best way after fact? add new migration creates :trackable_type index?

i figured out how make polymorphic association work case. not sure understand why, :as option has_many not used in polymorphic cases. instead must use standard :through option , reestablish polymorphism :source , :source_type options.

in example above, has_many statements in user model needed formatted follows:

has_many :tracked_widgets, :through => :tracks, :source => :trackable, :source_type => "widget" has_many :tracked_gadgets, :through => :tracks, :source => :trackable, :source_type => "gadget" has_many :tracked_nuggets, :through => :tracks, :source => :trackable, :source_type => "nugget" 

hopes helps trying address similar situation.


Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

php - Get uncommon values from two or more arrays -

Adding duplicate array rows in Php -