0

Just as on StackOverflow, in my app a User can write Questions and can also provide Answers:

class User < ActiveRecord::Base
  has_many :questions
  has_many :answers
end

class Question < ActiveRecord::Base
  has_many :answers
  belongs_to :user
end


class Answer < ActiveRecord::Base
  belongs_to :question
  belongs_to :user
end

My question has to do with the Answer model above:

Is it ok for an Answer to belong_to both the User and the Question models?

I have a feeling I read somewhere that a model can only have a single foreign key. If so, how do I rectify that?

Joe O'Driscoll
  • 289
  • 3
  • 13

1 Answers1

3

Yes, it is perfectly ok and you will have many models that have many belongs_to as your domain model gets more complex. I don't know where you would have read that a model can only have a single foreign key.

pjb3
  • 5,191
  • 5
  • 25
  • 44
  • Many people think that since a Class can only have 1 **parent** that models can only have 1 belongs_to. A misconception, but actually quite common. – colinross May 26 '11 at 09:30