2017-03-25 7 views
1

私にはuser,postcommentという3つのモデルがあります。'has_many through'アソシエーションから属性値を取得

userは、commentの1つにpostを掲示することができます。

postは、多くがcommentです。

私の質問は:

は、どのように私はポストのcommentcurrent_userの値を得ることができますか?私は私がそれを行うことができます知っている

# modle/user.rb 
has_many :comments 
has_many :posts through :comments 

# modle/post.rb 
has_many :comments 

# modle/comment.rb 
belongs_to :user 
belongs_to :post 

# in the controller 
@comments = current_user.comments 
@user_post_comment = @comments.where(:post_id => post_id).first 

まず、私はそれはそれを行うには、いくつかの良い方法でなければならないと思います。

第2に、あるページにいくつかの投稿がある可能性があるので、ビュー内の投稿を表示するには@posts.each do |post|のようにする必要があります。

を更新しました。そしてcurrent_user.post.comment好きです。

これはどのように行うのか知りたいです。

ご協力いただきありがとうございました!

は、私は以下のコードは、あなたは私が何をしたいのか理解するのに役立つことを願って2

を更新しました。

<%= @posts.each do |post| %> 
    <%= post.name %> 
    <%= how to show current_user comment of the post %> 
<% end %> 

ソリューション

そして今、私はこのような解決策があります。

# controller: 

@comments_by_curr_user = Comment. 
    where(post_id: @post.ids). # if paginate 
    where(user_id: current_user.id). 
    group_by(&:post_id) 


# view: 

<%= @posts.each do |post| %> 
    <%= post.name %> 
    <% @comments_by_curr_user[post.id].each do |comment| %> 
     ... ............. 
    <% end %> 
<% end %> 

はあなたの助けありがとうございました。

+0

をこのメソッドを使用する私はあなたを考えます間違ったアソシエーションを持っている – Vishal

+0

@Vishal私を見せてもらえますか? – floox

+0

質問にいくつかのタイプミスがあります。それは 'has_many:posts、through:comments'でなければなりません。 'has_many:comments'です。あなたはあなたの質問の説明にそれを修正する必要があります。 – etagwerker

答えて

0

@comments = current_user.posts.where(id: post_id).first.comments 

を試してみて、私はあなたがモデルの関係は

# modle/user.rb 
has_many posts 
has_many :comments 

# modle/post.rb 
has_many comments 

# modle/comment.rb 
belongs_to :user 
belongs_to :post 
+0

お返事ありがとうございます。なぜコメントモデルは 'belongs_to:user'を必要としませんでしたか? – floox

+0

@floox申し訳ありませんが、私の誤解のため、回答が編集されています。 – ashvin

+0

私は '@posts.each do | post |'のループを最初に実行し、 'current_user.post.comment'のようにしなければならないので、' @ comments'は必要ないかもしれません。 – floox

1

あなたはpost_idを持っている場合は、

current_user.comments.find_by(post_id: post_id) 

がそれにcurrent_userによって作られた単一のコメントを返しれるべきだと思います役職。あなたの2回目の更新に関しては

、あなたは多分この

# app/models/post.rb 
def find_comment_for_user(user) 
    user.comments.find_by(post_id: self.id) 
end 

ようになり、ポストモデルでヘルパーメソッドを作ることができる今、単にあなたのビューで

<%= @posts.each do |post| %> 
    <%= post.name %> 
    <%= post.find_comment_for_user(current_user) %> 
<% end %> 
+0

ありがとうございました。しかし、私はビューでそれを使用する方法について質問がありますか? 'current_user.comments.find_by(post_id:post_id)'はコントローラに書き込むべきですか? @Coolness – floox

+1

@floox、ええ、あなたはビューをレンダリングするコントローラメソッドでこれを使用し、結果をインスタンス変数、例えば '@ comment'に格納し、その変数をビューで使用するべきです。 – Coolness

+0

@Collness、私はそれがコントローラーでできることを知っています: '@comment = current_user.comments.find_by(post_id:post_id)'。ここで問題となるのは、ビューをレンダリングするコントローラー内で特別な 'post_id'を得るにはどうすればいいのですか?コントローラーで' @posts.each do | post | 'を使う' @ posts'しか得られません。 – floox

関連する問題