【问题标题】:Best way to scope a has_many relationship when find()'ing the parent object查找父对象时确定 has_many 关系范围的最佳方法
【发布时间】:2011-11-20 18:37:37
【问题描述】:

在我的测验应用程序中,我在理解默认范围和命名范围方面有些吃力。我在 Rails 3.0 上。

我有一个Question 模型has_many UserResponse 模型。

Question 有问题text 和可能的answer_idsUserResponseuser_id 绑定到 question_idanswer_id

当我将find()Question 显示给用户时,我不想同时拉动每个UserResponse。默认情况下,我只想拉出当前user_idUserResponse,看看他们是否已经回答了这个问题。

如何在QuestionUserResponse 上创建一个范围来完成此操作?

【问题讨论】:

    标签: ruby-on-rails-3 scope has-many named-scope default-scope


    【解决方案1】:

    不确定范围,但我可能会首先将模型关系与类似这样的查询一起使用:

    (给定问题和用户)

    responses = question(question).user_responses(user)
    

    然后,一旦工作正常,我将进入范围(如果需要)并拥有:

    用户模型的响应范围

    (Rails3 syntax)  scope :responses_by_user,  labmda { join(:responses) }
    

    回答问题模型的范围

    (Rails3 syntax)  scope :responses_by_question,  labmda { join(:responses) }  
    

    注意:我更倾向于这些“连接”方法,因为它们只会执行“内部”连接,即只返回确实存在响应记录的行。我这样做而不是更像lambda { where ('user_id = ?', User.id) } Then you could also chain them together. Something like Question.responses_by_question(question).responses_by_user(user)`的语法`

    【讨论】:

      猜你喜欢
      • 2014-02-25
      • 1970-01-01
      • 1970-01-01
      • 2014-08-08
      • 1970-01-01
      • 1970-01-01
      • 2018-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多