simas simas - 7 months ago 8
Ruby Question

Ruby on Rails - result printed as an object on my html

Here is my posts_controller.rb

class PostsController < ApplicationController
def index
@posts = Post.all.order("created_at DESC")
end

def new
end

def create
@post = Post.new(post_params)

@post.save
redirect_to @post
end

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

private
def post_params
params.require(:post).permit(:title, :body)
end
end


here is my index.html.erb

<%= @posts.each do |post| %>
<div class="post_wrapper">
<h2 class="title"><%= link_to post.title, post %></h2>
<p class="date"><%= post.created_at.strftime("%B, %d, %Y") %></p>
</div>
<% end %>


Here's how the page looks like:
screenshot

Why does that [ ] line show up ?
How do I hide/delete it ?

Answer

Change = to -:

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

You see in ERB <%= means print this into view, where as <%- says execute this ruby code.

Since everything in Ruby is an expression, your @posts.each do |post|; end %> block returns an array of @posts, which is then rendered into your view.

Comments