【问题标题】:Is this the proper way to setup a has_many through association?这是通过关联设置 has_many 的正确方法吗?
【发布时间】: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


【解决方案1】:

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

我对此的理解应该是这样的:

用户.rb

has_many :questions
has_many :answers

问题.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

【讨论】:

  • 这就是我最初所拥有的,但它不起作用,这就是为什么我添加 user_questions 具有许多关联。请在此处查看导致我这样做的原始帖子:stackoverflow.com/questions/20338551/…。我基本上只需要知道通过关联设置为 has_many 的正确方法。
  • 这是我的问题,哈哈,我只需要有人帮助验证我是否通过关联正确设置了 has_many。并复制了一段我原来的问题作为上下文;)
  • 考虑到所描述的问题,这种关联建模方式最有意义 - has_many through 是不必要的。
  • 虽然,考虑到这里的关联,通过答案做类似用户 has_many answers_questions 之类的事情可能是有意义的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-29
  • 1970-01-01
相关资源
最近更新 更多