Reputation: 35
While learning Ruby on rails, I'm trying to find a way to display posts inside communities, but I only managed to display the first post created inside the community
This is what I have so far
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
EDIT: Upon closer inspection I found that it will also display a post in community in which it doesn't belong if that community has no posts of it's own
Upvotes: 0
Views: 59
Reputation: 719
Please remove this line from your code, so your Post model will look like following -
class Post < ApplicationRecord
belongs_to :account
belongs_to :community
validates_presence_of :title, :body, :account_id, :community_id
end
Add above removed line in this file, so Community model will look like follow -
class Community < ApplicationRecord
belongs_to :account
validates_presence_of :url, :name, :rules
has_many :posts
end
Now use following code for show method -
def show
@posts = @community.posts
end
It'll solve the issue. Please let me know if you get any errors. Happy to help!
Upvotes: 1
Reputation: 2222
Since you are in the communities_controller
, you should look for a community:
def show
@community = Community.find(params[:id]
end
Once you have that, you can iterate through your @community.posts
in the show view:
<% @community.posts.each do |post| %>
<%= link_to post.title, community_post_path(@community, post) %>
<%= truncate post.body, length: 200 %>
<% end %>
You can also find the posts in the communities_controller
and then use those posts in the view:
def show
@community = Community.find(params[:id]
@posts = @community.posts
end
<% @posts.each do |post| %>
<%= link_to post.title, community_post_path(@community, post) %>
<%= truncate post.body, length: 200 %>
<% end %>
Also, if your community has no posts, you'll probably get an error page in your browser. You can use something like this to save you from that error:
<% if @community.posts.any? %>
<% @community.posts.each do |post| %>
<%= link_to post.title, community_post_path(@community, post) %>
<%= truncate post.body, length: 200 %>
<% end %>
<% else %>
<p>There are no posts for this community.</p>
<% end %>
You should also make sure you have community_id
in your posts table and you have your associations setup properly:
has_many :posts
belongs_to :community
Upvotes: 0
Reputation: 600
When you click a specific community link, the params[:id]
contains the id of that community. So you should use that id parameter for Community
model not the Post
. After finding that community record from DB you can get the posts like this:
def show
@community = Community.find(params[:id])
@posts = @community.posts
end
Upvotes: 1