1

我有一个 FormResponse,它belongs_to是一个 Form;表格然后has_many问题:

class FormResponse < ActiveRecord::Base
   belongs_to :form
end

class Form < ActiveRecord::Base
  has_many :form_responses
  has_many :questions
end

class Question < ActiveRecord::Base
end

当我发现自己questions在表单的上下文中需要很多时,我更喜欢在 FormResponse 上调用问题,如下所示:

form_response = FormResponse.find(id)
form_response.questions

为了使questions可用,我可以在 ActiveRecord 中执行此操作:

class FormResponse < ActiveRecord::Base
   belongs_to :form
   has_many :questions, :through => :form
end

或使用即时方法:

class FormResponse < ActiveRecord::Base
  belongs_to :form

  def questions
     self.form.questions unless self.form.nil?
  end
end

我对在 FormResponse 上设置问题不感兴趣(我不需要FormResponse.questions <<or 之类的东西FormResponse.questions.build),只是获取。

使用 over using 方法有什么好处,has_many :questions, :through => :form反之亦然?是否有诸如延迟加载、更好的 SQL 之类的好处?

AR 是否给出了关于何时使用 AR 关系以及何时简单地编写自己的方法的经验法则?

4

1 回答 1

0

我认为这更像是一个封装问题,而不是 ActiveRecord。

一般来说,我会在这里应用我的经验法则:

has_many :through当您真正想要对关系建模时使用。

当您要做的只是不违反Demeter 法则或保持代码 DRY 时,请实施委托方法。

于 2014-01-07T16:20:30.513 回答