【发布时间】:2016-11-21 16:17:06
【问题描述】:
我正在尝试在 has_many_through 关联中显示所有用户帖子上的所有 cmets。
routes.rb:
resources :posts do
resources :comments
end
型号:
class User < ActiveRecord::Base
has_many :posts, dependent: :destroy
has_many :comments, :through => :posts, dependent: :destroy
end
class Post < ActiveRecord::Base
belongs_to :user
has_many :comments, dependent: :destroy
end
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :post
end
users_controller.rb
def activity
@user = current_user
@posts = @user.posts
@comments = @user.comments
end
activity.html.erb
<h4>My Activity</h4>
<ol class="posts">
<%= render @comments.last(3) %>
</ol>
_comment.html.erb
<div class="comment" id="comment-<%= post.id %>-<%= comment.id %>">
<%= link_to smavatar_for(comment.user), user_path(comment.user.name) %>
<span class="user"><%= link_to comment.user.name, user_path(comment.user.name) %></span>
<div class="comment-content">
<%= simple_format(comment.content) %>
</div>
</div>
activity.html.erb 中的<%= render @comments.last(3) %> 行给出了错误
类的未定义局部变量或方法`post'
对于 _comment.html.erb 中的 <div class="comment" id="comment-<%= post.id %>-<%= comment.id %>"> 行。我知道我可能需要将局部变量传递给局部变量,我只是不知道该怎么做。 <%= @comments.last(3) %> 而不是 <%= render @comments.last(3) %> 将所有评论参数打印到视图中,因此它可以识别集合。添加locals: { comment: @comment, post: @post } 仍然得到我未定义的类局部变量帖子,而post: @comment.post 得到一个 nilClass 错误。我一直在研究 SO 和 RoR Guides 来回渲染局部,但我仍然不清楚何时通过什么,所以一般来说,任何帮助都是值得赞赏的。
【问题讨论】:
-
您是否也在同一页面中呈现帖子?我看不出你如何渲染 cmets 有任何问题
-
@Marv-C,我可以在同一页面上呈现帖子,并且它们呈现得很好,但我希望这个视图只呈现用户在他们的帖子中从其他人那里收到的 cmets。
标签: ruby-on-rails ruby-on-rails-4