私にはuser
,post
、comment
という3つのモデルがあります。'has_many through'アソシエーションから属性値を取得
各user
は、comment
の1つにpost
を掲示することができます。
各post
は、多くがcomment
です。
私の質問は:
は、どのように私はポストのcomment
current_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 %>
はあなたの助けありがとうございました。
をこのメソッドを使用する私はあなたを考えます間違ったアソシエーションを持っている – Vishal
@Vishal私を見せてもらえますか? – floox
質問にいくつかのタイプミスがあります。それは 'has_many:posts、through:comments'でなければなりません。 'has_many:comments'です。あなたはあなたの質問の説明にそれを修正する必要があります。 – etagwerker