![](/img/trans.png)
[英]Having trouble with RSpec 3.1.0 and has_many through relationship with Ruby-on-Rails 4.1
[英]Ruby-on-Rails: Multiple has_many :through possible?
是否有可能有多个has_many :through
在Rails中相互传递的关系? 我收到了这样的建议,作为我发布的另一个问题的解决方案,但一直无法让它工作。
好友是通过联接表的循环关联 。 目标是为friends_comments
创建一个has_many :through
,这样我就可以带一个User
并执行类似user.friends_comments
,以便在一个查询中获取他的朋友发表的所有评论。
class User
has_many :friendships
has_many :friends,
:through => :friendships,
:conditions => "status = #{Friendship::FULL}"
has_many :comments
has_many :friends_comments, :through => :friends, :source => :comments
end
class Friendship < ActiveRecord::Base
belongs_to :user
belongs_to :friend, :class_name => "User", :foreign_key => "friend_id"
end
这看起来很棒,而且很有意义,但不适合我。 当我尝试访问用户的friends_comments时,这是我在相关部分中遇到的错误:
ERROR: column users.user_id does not exist
: SELECT "comments".* FROM "comments" INNER JOIN "users" ON "comments".user_id = "users".id WHERE (("users".user_id = 1) AND ((status = 2)))
当我输入有效的user.friends时,这是它执行的查询:
: SELECT "users".* FROM "users" INNER JOIN "friendships" ON "users".id = "friendships".friend_id WHERE (("friendships".user_id = 1) AND ((status = 2)))
因此,它似乎完全忘记了原始的has_many
通过友谊关系,然后不恰当地尝试将User类用作连接表。
我做错了什么,或者这根本不可能?
编辑:
Rails 3.1支持嵌套关联。 例如:
has_many :tasks
has_many :assigments, :through => :tasks
has_many :users, :through => :assignments
不需要下面给出的解决方案。 有关详细信息,请参阅此截屏视频。
原始答案
您正在传递has_many :through
关联作为另一个has_many :through
来源的关联。 我认为它不会起作用。
has_many :friends,
:through => :friendships,
:conditions => "status = #{Friendship::FULL}"
has_many :friends_comments, :through => :friends, :source => :comments
您有三种方法可以解决此问题。
1)写一个关联扩展名
has_many :friends,
:through => :friendships,
:conditions => "status = #{Friendship::FULL}" do
def comments(reload=false)
@comments = nil if reload
@comments ||=Comment.find_all_by_user_id(map(&:id))
end
end
现在您可以获得以下朋友评论:
user.friends.comments
2)向User
类添加方法。
def friends_comments(reload=false)
@friends_comments = nil if reload
@friends_comments ||=Comment.find_all_by_user_id(self.friend_ids)
end
现在您可以获得以下朋友评论:
user.friends_comments
3)如果您希望这更有效,那么:
def friends_comments(reload=false)
@friends_comments = nil if reload
@friends_comments ||=Comment.all(
:joins => "JOIN (SELECT friend_id AS user_id
FROM friendships
WHERE user_id = #{self.id}
) AS friends ON comments.user_id = friends.user_id")
end
现在您可以获得以下朋友评论:
user.friends_comments
所有方法都缓存结果。 如果要重新加载结果,请执行以下操作:
user.friends_comments(true)
user.friends.comments(true)
或者更好的是:
user.friends_comments(:reload)
user.friends.comments(:reload)
有一个插件可以解决您的问题,看看这个博客 。
你安装插件
script/plugin install git://github.com/ianwhite/nested_has_many_through.git
虽然这在过去不起作用,但它现在在Rails 3.1中运行良好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.