我试图在一个查询中获取用户朋友的所有帖子和用户信息。
我尝试过使用include(:use ),但这似乎不起作用,并引发了一个错误。我认为手动连接是最好的解决方案:
@friends = @user.friends
.joins('inner join users on users.id = friends.user_id left outer join posts on users.id = posts.user_id')
.select('posts.*, users.*, friends.*')如何从用户和帖子中访问属性?执行@friends.inspect只显示来自朋友表的属性,而我不能执行@friends.posts或@friends.users。
我的朋友和用户模型如下:
class Friend < ActiveRecord::Base
belongs_to :users
end
class User < ActiveRecord::Base
has_many :friends
has_many :users, through: :friends
end发布于 2015-02-28 04:33:20
根据join子句中的SQL,您的posts与users有关,而不是friends。像这样的东西会有用的:
friends.map{|f| f.user.posts}.flatten 如果朋友有belongs_to :user (单数"user"),这将是常规的Rails,并且反映在您使用的SQL中,那么正确的首要因素也是如此。
https://stackoverflow.com/questions/28734385
复制相似问题