3

私は(ポリモーフィック)オブジェクト(およびオブジェクトCommentに使用されます)を持っています。のs:のすべてを取得するにはどうすればよいですか? メソッドは に対して未定義であると書かれています。それを機能させる簡単な方法はありますか?多対多の関係ですか。多くの車両には多くのコメントがありますか? それとも私が間違っていますか?正常に動作します。 VehicleReviewcommentsUserVehicle@user.vehicles.commentscommentsActiveRecord::Relation@user.vehicles.first.comments

オブジェクト間の関係 (完全ではありません):

User 
has_many Vehicles. 

Vehicle 
belongs_to User. 
has_many Comments (as commentable). 

Comment 
belongs_to Commentable, :polymorphic => true
4

4 に答える 4

5

コメント部分だけでも結構です。事は - あなたが呼んでいる:

@user.vehicles.comments

ここで、車両は、コメントについて何も知らない AR 関係オブジェクトです。つまり、@user.vehicles は、そのユーザーの車両のコレクションです。

ユーザーにリンクされた車両に関するすべてのコメントを取得するには、次のようにします。

@user.vehicles.to_a.collect{|v| v.comments.to_a }.flatten

これは、ユーザーの車両に関するすべてのコメントの配列を返します。

于 2012-11-19T11:44:03.680 に答える
2

これを試して:

これをuser.rbに書き込みます。

    has_many :comments, :through => :vehicles

今やる

 @user.comments  

それはあなたの車のために作成されたすべてのコメントをフェッチします

次の方法でコメントを取得することもできます。

    @user.vehicles(:include => :comments).collect{|v| v.comments}.flatten

しかし、私の意見では、これは正しい方法ではありません。

于 2012-11-19T12:27:44.163 に答える
1

複雑な関連付けを試みているか、多態的な関連付けについて誤解していると思います。思ったより簡単です。定義する必要のある関連付けは次のとおりです。

User 
has_many vehicles 

Vehicle 
belongs_to user 
has_many comments, as: :commentable

Comment 
belongs_to :commentable, polymorphic: true

has_many :throughユーザーの車両に関するすべてのコメントを取得するには、ユーザーモデルで関連付けを定義します。

User 
has_many vehicles 
has_many comments, through: :vehicles

@user.commentsこれで、ユーザーの車両に関するすべてのコメントを取得するために使用できます。

于 2012-11-19T10:37:04.947 に答える
1

これを試してください:

ユーザーモデルに追加:

has_many :comments, :through => :vehicles

車両とレビューのために編集:

ユーザーモデルの場合:

has_many :comments, :through => :vehicles, :as => :comments_vehicles
has_many :comments, :through => :reviews, :as => :comments_reviews

def comments
  self.comments_vehicles + self.comments_reviews
end
于 2012-11-19T10:37:13.487 に答える