Nauman Zafar Nauman Zafar - 6 months ago 11
Ruby Question

Issue with Query Response sent to view - Rails

I am pretty new to Rails. I've a two controllers Users and Posts. Show method of User controller is as follows.

users_controller.rb

def show
@user = User.find(params[:id])
end


show.html.erb

<p>
<strong>First Name:</strong>
<%= @user.first_name %>
</p>

<p>
<strong>Last Name :</strong>
<%= @user.last_name %>
</p>

<p>
<strong>Age :</strong>
<%= @user.age %>
</p>

<p>
<strong>Created At</strong>
<%= @user.created_at %>
</p>

<h3> All Posts By <%= @user.first_name %> </h3>

<%= @user.posts.each do |post| %>

<li> <%= post.post_desc %> </li><br/>

<% end %>


Everything goes fine as per the code, but query response is also appended like this. stack_ques_reference_image

If you see the image below is appended

[#<Post id: 2, user_id: 2, created_at: "2016-05-08 17:39:39", updated_at: "2016-05-08 17:39:39", post_desc: "Another post">, #<Post id: 3, user_id: 2, created_at: "2016-05-08 17:39:50", updated_at: "2016-05-08 17:39:50", post_desc: "Another post just to show post">, #<Post id: 9, user_id: 2, created_at: "2016-05-09 09:58:54", updated_at: "2016-05-09 09:58:54", post_desc: "Hello oye">, #<Post id: 10, user_id: 2, created_at: "2016-05-09 10:00:04", updated_at: "2016-05-09 10:00:04", post_desc: "Yummy Post by faizan">]


Any pointer to the solution and reason for this issue will be much appreciated. Thanks.

Answer

You are printing array of objects

<%= @user.posts.each do |post| %>

    <li> <%= post.post_desc %> </li><br/>

 <% end %>

Just run each on the array by <%= @user.posts.each do |post| %> replacing with <% @user.posts.each do |post| %>

 <% @user.posts.each do |post| %>

    <li> <%= post.post_desc %> </li><br/>

 <% end %>