I have a blog app backed with Rails. I have Posts
and Comments
tables. Both are connected with has many - belongs to
relationship, also resources are nested in config/routes.rb
. In my posts#show
, I'd like to call comments related with the post. I've written codes like below. But I got some errors like Couldn't find Comment without an ID
. Here are my codes related with this issue:
# app/controllers/posts_controller.rb
def show
@post = Post.find(params[:id])
@comments = Comment.find(params[:post_id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @post }
end
end
# app/views/posts/show.html.erb
<h3><%= @post.title.titleize %></h3>
<p><%= @post.content %></p>
<% if @comments %>
<% @comments.each do |com| %>
<h4><%= com.title.titleize %></h4>
<p><%= com.content %></p>
<hr />
<% end %>
<% else %>
<p>No Comments Found , <%= link_to 'Add One?', new_post_comment_path(@post) %></p>
<% end %>
<%= link_to 'Edit', edit_post_path(@post) %> |
<%= link_to 'Back', posts_path %>
# config/routes.rb
resources :posts do
resources :comments
end
EDIT:
Now I've used includes(:comments)
in posts_controller.rb
:
# app/controllers/posts_controller.rb
def show
@post = Post.includes(:comments).find(params[:id])
#@comments = Comment.find(params[:post_id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @post }
end
end
Also I've updated show.html.erb
respectively:
<h3><%= @post.title.titleize %></h3>
<p><%= @post.content %></p>
<% if @post.comments %>
<% @post.comments.each do |com| %>
<h4><%= com.title.titleize %></h4>
<p><%= com.content %></p>
<hr />
<% end %>
<% else %>
<p>No Comments Found , <%= link_to 'Add One?', new_post_comment_path(@post) %></p>
<% end %>
<%= link_to 'Edit', edit_post_path(@post) %> |
<%= link_to 'Back', posts_path %>
And here's new error:
PG::Error: ERROR: column comments.commentable_type does not exist LINE 1: SELECT "comments".* FROM "comments" WHERE "comments"."comme... ^ : SELECT "comments".* FROM "comments" WHERE "comments"."commentable_type" = 'Post' A...