如何解决如何显示某个社区的帖子? communities_controller.rb communities / show.html.erb communities_controller communities / show.html.erb community.rb post.rb
在学习Ruby on Rails的同时,我试图找到一种在社区内显示帖子的方法,但是我只设法显示了在社区内创建的第一篇帖子
这是我到目前为止所拥有的
communities_controller.rb:
def show
if params[:id]
@posts = Post.where("id = ?",params[:id])
else
@posts = Post.all
end
end
show.html.erb:
<% @posts.each do |post| %>
<%= link_to post.title,community_post_path(@community,post) %>
<%= truncate post.body,length: 200 %>
<% end %>
routes.rb:
resources :communities do
resources :posts
end
编辑:仔细检查后发现,如果该社区没有自己的帖子,它还将在社区中显示不属于该帖子的帖子
解决方法
当您单击特定的社区链接时,params[:id]
包含该社区的ID。因此,您应该为Community
模型而不是Post
使用该id参数。从数据库中找到该社区记录后,您将获得如下信息:
def show
@community = Community.find(params[:id])
@posts = @community.posts
end
,
请从您的代码中删除this line,以便您的Post模型如下所示-
class Post < ApplicationRecord
belongs_to :account
belongs_to :community
validates_presence_of :title,:body,:account_id,:community_id
end
在this file中的删除行上方添加,因此社区模型将如下所示-
class Community < ApplicationRecord
belongs_to :account
validates_presence_of :url,:name,:rules
has_many :posts
end
现在将以下代码用于show方法-
def show
@posts = @community.posts
end
它将解决问题。如果您遇到任何错误,请告诉我。乐意提供帮助!
,由于您位于communities_controller
,因此您应该寻找一个社区:
communities_controller.rb
def show
@community = Community.find(params[:id]
end
有了这些,就可以在显示视图中迭代@community.posts
:
communities / show.html.erb
<% @community.posts.each do |post| %>
<%= link_to post.title,community_post_path(@community,post) %>
<%= truncate post.body,length: 200 %>
<% end %>
您还可以在communities_controller
中找到这些帖子,然后在视图中使用这些帖子:
communities_controller
def show
@community = Community.find(params[:id]
@posts = @community.posts
end
communities / show.html.erb
<% @posts.each do |post| %>
<%= link_to post.title,length: 200 %>
<% end %>
此外,如果您的社区中没有帖子,则可能会在浏览器中显示错误页面。您可以使用类似的方法来避免出现该错误:
<% if @community.posts.any? %>
<% @community.posts.each do |post| %>
<%= link_to post.title,post) %>
<%= truncate post.body,length: 200 %>
<% end %>
<% else %>
<p>There are no posts for this community.</p>
<% end %>
您还应该确保自己的帖子表中有community_id
,并且已正确设置关联:
community.rb
has_many :posts
post.rb
belongs_to :community
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。