这个SQL在MetaWhere中怎么写呢?
我如何使用 MetaWhere (在 Rails 3 中)编写此查询?
SELECT "users".* FROM "users"
INNER JOIN "friendships" friends
ON "users"."id" = friends."friend_id"
INNER JOIN "friendships" inverse_friends
ON "users"."id" = inverse_friends."user_id"
WHERE friends."user_id" = 4
AND friends."status" = 't'
AND inverse_friends."friend_id" = 4
AND inverse_friends."status" = 't'
我正在尝试在我的 User
类上添加一个名为 buddies
的方法,该方法将返回 friends
和 inverse_friends
这个自引用关联上的 Railscast。
我将不胜感激任何帮助!
编辑:我希望能够查询返回的集合,这样我就可以执行以下操作:
def is_a_buddy_of?(user)
not self.buddies.where(:friend_id >> user.id).empty?
end
解决方案:没关系最后一次编辑,我只是使用 is_a_buddy_of?(user)
方法对此进行了修改code>| 运算符对我现有的关联:
def is_a_buddy_of?(user)
status = false
self.buddies.map do |buddy|
status = true if buddy.id == user.id
end
status
end
How would I write this query using MetaWhere (in Rails 3)?
SELECT "users".* FROM "users"
INNER JOIN "friendships" friends
ON "users"."id" = friends."friend_id"
INNER JOIN "friendships" inverse_friends
ON "users"."id" = inverse_friends."user_id"
WHERE friends."user_id" = 4
AND friends."status" = 't'
AND inverse_friends."friend_id" = 4
AND inverse_friends."status" = 't'
I'm trying to add a method on myUser
class called buddies
that will return both friends
and inverse_friends
from this Railscast on self-referential association.
I'd appreciate any help!
EDIT: I want to be able to query on the returned set, such that I can do:
def is_a_buddy_of?(user)
not self.buddies.where(:friend_id >> user.id).empty?
end
SOLUTION: Nevermind that last edit, I just modified my is_a_buddy_of?(user)
method to this, using the |
operator on my existing associations:
def is_a_buddy_of?(user)
status = false
self.buddies.map do |buddy|
status = true if buddy.id == user.id
end
status
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么不在用户模型中执行以下操作?:
|
是联合运算符。why don't you just do the following in your User model?:
|
is the union operator.