在 Rails 3 中使用连接获取数据的范围 [英] Scope with joins to get data in Rails 3
问题描述
从 Rails 2 到 Rails 3,我从未如此努力地理解某些东西(旁注).
Coming from Rails 2 to Rails 3 I've never worked so hard to understand something (side editorial).
无论如何,在 Rails 3 应用程序中,我有以下模型......
Anyway, In a Rails 3 app i have the following models...
用户:
has_many :answers
答案:
belongs_to :user
belongs_to :question
scope :user_answers, where (:user_id => current_user.id)
问题:
has_many :answers
scope :qs_w_user_ans, joins(:questions) & (:user_answers)
我得到的当前错误是未定义方法`includes_values' for :user_answers:Symbol"
The current error i am getting is "undefined method `includes_values' for :user_answers:Symbol"
有一个问题 ID 和一个用户 ID.每个答案都有 question_id 和 user_id.
There is a Question id and a User id. Each answer has question_id and user_id.
我需要通过 id 适当链接用户答案的问题.你能告诉我我的模型哪里错了吗?
I need the questions with a user's answers linked appropriately via the ids. Can you show me where my models are wrong?
谢谢.
推荐答案
&
运算符(我认为最近已弃用)是 merge
的别名,它允许您基本上合并范围.:user_answers
不是范围,因此您不能使用此方法.
The &
operator (which I believe is recently deprecated) is an alias for merge
, which allows you to essentially merge scopes. :user_answers
isn't a scope, so you can't use this method.
正如 Dinatih 所指出的,您可以多次调用连接.在这种情况下,为每个连接创建不同的范围不会给您带来太多好处,因此他的方法适合您的情况.
As Dinatih pointed out, you can call joins multiple times. In this case, creating different scopes for each join won't buy you much, so his method suits your case.
更新
对不起,我的误解.:user_answers
是一个范围,但在这种情况下您没有正确调用它.您需要以下内容:
Sorry for my misunderstanding. :user_answers
is a scope, but you're not calling it correctly in this case. You want the following:
scope :qs_w_user_ans, joins(:questions) & Answer.user_answers
合并作用域时,您可以像调用类方法一样调用合并的作用域.
When merging scopes, you call the merged scopes like class methods.
在我链接的文章中,Post
上的范围 :published
与 User上的范围
:published
合并代码>:
In the article I linked, the scope :published
on Post
is merged with the scope :published
on User
:
scope :published, lambda {
joins(:posts).group("users.id") & Post.published
}
这篇关于在 Rails 3 中使用连接获取数据的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!