Ruby on Rails:複数のhas_manyにより可能ですか?
-
24-09-2019 - |
質問
可能です複数の has_many :through
関係として、ご提供いただいた各レール?頂いたご提案いソリューションとしてその掲載ができていないが得られます。
友人とは 環状協会 を通じて参加。の目標を has_many :through
のための friends_comments
, いままで 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)))
もっとも入ります。友達を作り、これはクエリが実行さ:
: SELECT "users".* FROM "users" INNER JOIN "friendships" ON "users".id = "friendships".friend_id WHERE (("friendships".user_id = 1) AND ((status = 2)))
いまだ完全に忘れての has_many
を通じて友好関係、それが不正に利用しようと、ユーザークラスとして参加。
にしてるわけではありませんので、異物混入など異常が認は、このメソッドは単純ない可能ですか?
解決
編集:
レール3.1対応の子会例:
has_many :tasks
has_many :assigments, :through => :tasks
has_many :users, :through => :assignments
必要がないために解決します。参照 この screencastます。
独自の回答
お手 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で正常に動作します。