【发布时间】:2013-12-03 01:45:12
【问题描述】:
所以我有 4 个模型..
一个 User 模型、一个 Question 模型、一个 Answer 模型和一个 User_Question 模型。
现在我创建了适用于所有用户的默认种子问题,即@questions = Question.all
每个用户都可以看到这些相同的问题,现在我如何允许每个用户在这些问题与问题没有直接关联时编写自己的答案?我得到了一个通过关联创建 has_many 的解决方案,我只是想确保我已正确设置它,请参阅下面的代码,谢谢:
user.rb
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :user_questions
has_many :questions, through: :user_questions
end
answer.rb
class Answer < ActiveRecord::Base
attr_accessible :answer
has_many :user_questions
has_many :questions, through: :user_questions
end
question.rb
class Question < ActiveRecord::Base
attr_accessible :title, :body
belongs_to :user
has_one :answer
end
user_question.rb
class UserQuestion < ActiveRecord::Base
belongs_to :user
belongs_to :question
belongs_to :answer
end
【问题讨论】:
-
为什么会有user_question?
-
感谢@ShaunFrostDukeJackson,我使用它是因为我的问题独立于用户而存在,所以我通过 user_questions 关联创建了一个用户 has_many questions,它是一个中间表,其中包含用户和问题的外键。所以一个 UserQuestion 可以属于一个答案。不确定它是否设置正确。您能否验证一下,这是我第一次通过关联使用 has_many。
标签: ruby-on-rails ruby-on-rails-3 activerecord ruby-on-rails-4