这是通过关联设置has_many的正确方法吗?

时间:2013-12-03 01:45:12

标签: ruby-on-rails ruby-on-rails-3 activerecord ruby-on-rails-4

所以我有4个模特..

用户模型,问题模型,答案模型和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

1 个答案:

答案 0 :(得分:1)

如果我理解正确,您说您的问题独立于用户而存在。然而问题属于用户。

我对此的理解应该如下:

User.rb

has_many :questions
has_many :answers

question.rb

belongs_to :user
has_many :answers

answer.rb

belongs_to :question
belongs_to :user

注意复数以及belongs_to和has_many。

指南的链接在这里,但我认为您不需要user_questions。

http://guides.rubyonrails.org/association_basics.html#the-has-many-association

相关问题