Well the situation is bit more complicated than that !
I have a question model
class Question < ActiveRecord::Base
has_many :answers, :dependent => :destroy
then an answer Model
class Answer < ActiveRecord::Base
belongs_to :question, :counter_cache => true
has_many :rep_events, :class_name => "RepEvent", :foreign_key => "event_id", :dependent => :destroy
and Finaly a rep_event model
class RepEvent < ActiveRecord::Base
开发者_C百科 belongs_to :answer
end
My rep event doesnt have any primary key. it only has event_id that acts like answer_id
When i destroy a Question, I want to delete everything that is related to it ( Question, Answers and Rep_Events ) Thats why I'm using :dependent => :destroy
I tried to enter the console and test it but it gives me some error
NoMethodError: undefined method `eq' for nil:NilClass
This error is very general but I believe the problem is that my rep_event class does not have any "answer_id" field but only event_id. thats why I used foreign_key => "event_id" in my relationship.
Can anyone tell me what the problem is ?
Thank you
The foreign key is not present in the Answer model, instead RepEvent model has a foreign key called 'event_id' that acts like answer_id, and links to the Answer model. If this scenario is right you will have to do following changes in the RepEvent model
class RepEvent < ActiveRecord::Base
belongs_to :answer, :foreign_key => event_id
end
and in your Answer model
class Answer < ActiveRecord::Base
belongs_to :question, :counter_cache => true
has_many :rep_events, :class_name => "RepEvent", :dependent => :destroy
end
Try this this must work.
精彩评论