Reputation: 132
I am trying to create a simple blog app using simple_form
In my new.html.erb for Post, I have the following code
<h3>Write your blog post here</h3>
<%= simple_form_for @post do |f| %>
<%= f.input :content %><br>
<%= f.submit %>
<% end %>
In index.html.erb, I got
<%= @posts.each do |post| %>
<p>Post: <%= post.content %></p>
<% end %>
However, I am getting the following on my index page for Post
[#<Post id: 1, created_at: "2015-09-07 23:07:54", updated_at: "2015-09-07 23:07:54", content: nil>, #<Post id: 2, created_at: "2015-09-07 23:07:54", updated_at: "2015-09-07 23:07:54", content: nil>, #<Post id: 3, created_at: "2015-09-07 23:08:11", updated_at: "2015-09-07 23:08:11", content: nil>,
Here is my Post Controller
def index
@posts = Post.all
end
def show
@post = Post.find(params[:id])
end
def new
@post = Post.new
end
def create
@post = Post.new(params[post_params])
if @post.save
success = true
message = "Nice!"
else
success = false
message = "Sucks!"
end
redirect_to root_path
end
private
def post_params
params.require(:post).permit(:content)
end
end
Here is my model
class Post < ActiveRecord::Base
belongs_to :user
end
And finally, the migration to add content column to Post
class AddContentToPosts < ActiveRecord::Migration
def change
add_column :posts, :content, :string
end
end
After typing the text in my Post, I am able to create it. But I am not sure if it's being saved as the content says "nil". This is very frustrating as it seems like a very simple problem. After hours of trying to figure out what's going on, asking for help here... Thank you!
Upvotes: 0
Views: 355
Reputation: 239290
You have two problems:
First, this line:
<%= @posts.each do |post| %>
Needs a <%
, not a <%=
.
<%=
outputs the result of the expression. The result of array.each
is an array, and that's what you're seeing the browser.
Second, your accessing of params
is wrong. You're using
@post = Post.new(params[post_params])
You use params[:post]
, or you use post_params
, but you don't do both. You're trying to use the return value of post_params
, which is an Hash of keys and values, as a key to access params
again. You need either of these:
@post = Post.new(params[:post])
# or
@post = Post.new(post_params)
Upvotes: 1