具有连接的范围以在Rails 3中获取数据

Jay*_*Jay 12 ruby-on-rails-3

从Rails 2到Rails 3我从来没有努力去理解某些东西(侧面编辑).

无论如何,在Rails 3应用程序中,我有以下型号......

用户:

has_many :answers
Run Code Online (Sandbox Code Playgroud)

回答:

belongs_to :user
belongs_to :question
scope :user_answers, where (:user_id => current_user.id)
Run Code Online (Sandbox Code Playgroud)

题:

has_many :answers
scope :qs_w_user_ans, joins(:questions) & (:user_answers)
Run Code Online (Sandbox Code Playgroud)

我得到的当前错误是"未定义的方法`includes_values':user_answers:Symbol"

有一个问题ID和一个用户ID.每个答案都有question_id和user_id.

我需要通过ID正确链接用户答案的​​问题.你能告诉我我的模特哪里错了吗?

谢谢.

McS*_*tch 15

&运营商(我相信是近期不建议使用)是一个别名merge,它允许你完全合并范围.:user_answers不是范围,因此您无法使用此方法.

正如Dinatih指出的那样,你可以多次调用连接.在这种情况下,为每个连接创建不同的范围对您来说不会太多,所以他的方法适合您的情况.

有关范围的更多信息:http://archives.edgerails.info/articles/what-s-new-in-edge-rails/2010/02/23/the-skinny-on-scopes-formerly-named-scope/index html的

更新

对不起我的误会.:user_answers是一个范围,但在这种情况下你没有正确地调用它.您需要以下内容:

scope :qs_w_user_ans, joins(:questions) & Answer.user_answers
Run Code Online (Sandbox Code Playgroud)

合并作用域时,可以像类方法一样调用合并的作用域.

在这篇文章中我联系,范围:publishedPost与合并范围:publishedUser:

scope :published, lambda {
  joins(:posts).group("users.id") & Post.published
}
Run Code Online (Sandbox Code Playgroud)