我有很多用户,如何只列出一个帖子,还显示其他用户的所有评论?
发布模型
belongs_to :user
has_many :comments
Run Code Online (Sandbox Code Playgroud)
评论模型
belongs_to :post
belongs_to :user
Run Code Online (Sandbox Code Playgroud)
用户模型
has_many :posts
has_many :comments
Run Code Online (Sandbox Code Playgroud)
的routes.rb
resources :posts do
resources :comments
end
Run Code Online (Sandbox Code Playgroud)
在控制器中
def index
@post = User.posts.all
@comment = User.comments.all
end
Run Code Online (Sandbox Code Playgroud)
在视图index.html.erb中
<%@post.each do |post|%>
<%=post.post_name %>
<%= post.post_description %>
<%end%>
<%@comment.each do |comment|%>
<%=comment.content %>
<%end%>
Run Code Online (Sandbox Code Playgroud)
如何仅显示当前用户的帖子和评论?