Reputation: 953
I have a double polymorphic associations, basically i'm going to put in relation Questions model and VideoInterview model with Bond model. They are made in this way:
bond migration
class CreateBonds < ActiveRecord::Migration
def change
create_table :bonds do |t|
t.references :sourceable, :polymorphic => true
t.references :targetable, :polymorphic => true
t.string :operation
t.string :score
t.timestamps
end
end
end
bond.rb
class Bond < ActiveRecord::Base
belongs_to :sourceable, :polymorphic => true
belongs_to :targetable, :polymorphic => true
end
question.rb
class Question < ActiveRecord::Base
has_many :bonds, :as => :sourceable
has_many :bonds, :as => :targetable
end
video_interview.rb
class VideoInterview < ActiveRecord::Base
has_many :bonds, :as => :sourceable
has_many :bonds, :as => :targetable
end
How should i modify the model in orders to user this association correctly? If I call @question.bonds, I think there is something wrong because sourceable and targetable are defined under the same has_many :bonds. I'd like ti make @question.sources and get all the bonds with the question as sourceable element. Thank you
Upvotes: 2
Views: 835
Reputation: 7227
you need have different names for your associations, naming both the associations bonds in case of sourceable and targetable will not work for you. you can name it any thing and provide a class_name to associate with bond model like this for the Question model
class Question < ActiveRecord::Base
has_many :sources, :class_name => 'Bond', :as => :sourceable
has_many :targets, :class_name => 'Bond', :as => :targetable
end
and similarly for the VideoInterview Model
class VideoInterview < ActiveRecord::Base
has_many :sources, :class_name => 'Bond', :as => :sourceable
has_many :targets, :class_name => 'Bond', :as => :targetable
end
now you can call functions like this @question.sources, @question.targets, @video_interview.sources, @video_interview.targets
hope that helps.
Upvotes: 2