Wil*_*nes 1 sql join ruby-on-rails find
想象一下像模特这样的用户谁拥有很多朋友,每个人都有很多评论,我试图向用户显示他的朋友最新的100条评论.
是否有可能在单个SQL查询中绘制最新的100,或者我将不得不使用Ruby应用程序逻辑来解析更大的列表或进行多个查询?
我看到了两种解决方法:
编辑:我很难让EmFi的解决方案工作,并且会欣赏任何人都可以提供的任何见解.
好友是通过联接表的循环关联.
has_many :friendships
has_many :friends,
:through => :friendships,
:conditions => "status = #{Friendship::FULL}"
Run Code Online (Sandbox Code Playgroud)
这是我在相关部分得到的错误:
错误:列users.user_id不存在
: SELECT "comments".* FROM "comments" INNER JOIN "users" ON "comments".user_id = "users".id WHERE (("users".user_id = 1) AND ((status = 2)))
Run Code Online (Sandbox Code Playgroud)
当我刚进入user.friends,它工作时,这是它执行的查询:
: SELECT "users".* FROM "users" INNER JOIN "friendships" ON "users".id = "friendships".friend_id WHERE (("friendships".user_id = 1) AND ((status = 2)))
Run Code Online (Sandbox Code Playgroud)
因此,似乎它正在破坏:通过在一个查询中有两个:through.
鉴于以下关系:
class User < ActiveRecord::Base
has_many :friends
has_many :comments
has_many :friends_comments, :through => :friends, :source => :comments
end
Run Code Online (Sandbox Code Playgroud)
该语句将执行单个SQL语句.关联实际上为您创建了命名范围,直到链的末尾才对其进行求值.
@user.friends_comments.find(:limit => 100, :order => 'created_at DESC')
Run Code Online (Sandbox Code Playgroud)
如果这是一个常见查询,则可以将查找简化为其自己的范围.
class Comments < ActiveRecord::Base
belongs_to :user
#named_scope was renamed to scope in Rails 3.2. If you're working
#if you're working in a previous version uncomment the following line.
#named_scope :recent, :limit => 100, : order => 'created at DESC'
scope :recent, :limit => 100, :order => 'created_at DESC'
end
Run Code Online (Sandbox Code Playgroud)
所以现在你可以这样做:
@user.friends_comments.recent
Run Code Online (Sandbox Code Playgroud)
注意:用户上的朋友关联可能是通过连接表的循环关联,但这对此解决方案并不重要.只要朋友是User上的工作关联,前面的工作就可以了.
| 归档时间: |
|
| 查看次数: |
3320 次 |
| 最近记录: |