Ruby on rails 从';通过';协会
我有三种模式:Ruby on rails 从';通过';协会,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,我有三种模式:user、post和comment 每个用户都可以向一个用户发布一条评论 每个帖子都有许多评论s 我的问题是: 如何获取当前用户的帖子评论值 # model/user.rb has_many :comments has_many :posts through :comments # model/post.rb has_many :comments # model/comment.rb belongs_to :user belongs_to :post 我知道我可以用: # i
user
、post
和comment
每个用户
都可以向一个用户发布一条评论
每个帖子
都有许多评论
s
我的问题是:
如何获取当前用户的帖子评论值
# model/user.rb
has_many :comments
has_many :posts through :comments
# model/post.rb
has_many :comments
# model/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
首先,我认为这一定是更好的方法
其次,因为一个页面中可能有一些帖子,所以我必须执行类似于@posts.each do | post |
的操作才能在视图中显示帖子
已更新
然后像当前用户.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 %>
#控制器:
@comments\u by\u curr\u user=注释。
其中(post_id:@post.id)。#如果分页
其中(user\u id:current\u user.id)。
分组人(&:post_id)
#视图:
... .............
谢谢大家的帮助。试试看
@comments = current_user.posts.where(id: post_id).first.comments
我认为你们的关系模式应该是
# model/user.rb
has_many posts
has_many :comments
# model/post.rb
has_many comments
# model/comment.rb
belongs_to :user
belongs_to :post
如果您有post\u id
,则
current_user.comments.find_by(post_id: post_id)
返回当前用户对该帖子发表的单个评论
至于您的第二次更新,您可以在post模型中创建一个助手方法,看起来可能类似于
# 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 %>
我想你错了association@Vishal你能给我看一下吗?你的问题有几个拼写错误。应该是有很多:帖子,通过:评论
有很多:注释
。您应该在问题的描述中解决这个问题。@etagwerker谢谢您,已更新。谢谢您的回复。为什么评论模型不需要属于:user
?@floox很抱歉我理解错误,答案已经编辑好了。也许我不需要@comments
,因为我必须先循环@posts.each do | post |
,然后像当前用户.post.comment
。你到底想要什么,你能更新你的问题吗?谢谢,看起来很有效。但我有一个问题,如何在视图中使用它<代码>当前用户。注释。查找人(post\u id:post\u id)
是否应写入控制器@Coolness@floox,是的,您应该在呈现视图的控制器方法中使用它,将结果存储在实例变量中,例如@comment
,并在视图中使用该变量。@Collness,我知道它可以在控制器中完成:@comment=current\u user.comments.find\u by(post\u id:post\u id)
。现在的问题是:如何在呈现视图的控制器中获取特殊的post\u id
,我只能获取将使用@posts的@posts
。每个人都在控制器中进行post
。也就是说,在控制器中,我只能获取@posts
,然后当@posts
呈现在视图中时,我可以得到@post.id
。如何解决这个问题?多谢各位@Coolnes。