0

I have a pretty simple User/Posts controller. a User has many Posts, and on a user's "show" page they have the ability to make a post (Similar to a "Facebook" status. Anyways here is my controllers and view (each controller only has 1 action right now since I just started writing it:

user_controller

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

posts_controller

  def create
    user = current_user
    @post = user.posts.new(post_params)
    @post.save
    flash.notice = "Post successfully saved"
    redirect_to current_user
  end

user "show" view:

<%= @user.email %>
<%= @user.first_name %>


<%= @posts.each do |post| %>
<p>
  <%= post.content %>
</p>
<% end %>


<%= form_for @post do |f| %>
  <%= f.text_field :content %>
  <%= f.submit "Create" %>
<% end %>

So everything works fine, but on my show page pretend the user has 3 "posts" ["Test 1", "Test 2", "Test 3"]. I see all 3 of them but at the end I also see an array with ALL of them. That looks like this on the page:

Test 1

Test 2

Test 3

[#<Post id: 6, content: "Test 1", user_id: 1, created_at: "2019-02-10 06:49:15", updated_at: "2019-02-10 06:49:15">, #<Post id: 7, content: "Test 2", user_id: 1, created_at: "2019-02-10 06:49:19", updated_at: "2019-02-10 06:49:19">, #<Post id: 8, content: "Test 3", user_id: 1, created_at: "2019-02-10 06:49:22", updated_at: "2019-02-10 06:49:22">]

Which doesn't make sense to me. Why is that last item appearing?

msmith1114
  • 2,717
  • 3
  • 33
  • 84

1 Answers1

2

It should be <% @posts.each do | post| %>

Adding the equal sign into the opening erb tag will display those contents to the view.

vinyl
  • 490
  • 4
  • 8