Reputation: 149
I'm trying to build a simple blog on rails 5
. I have created a post model:
create_table "posts", force: :cascade do |t|
t.string "title"
t.text "body"
t.integer "category_id"
t.integer "author_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
And my controller methods:
def new
@post = Post.new
@categories = Category.all
end
def create
@post = Post.new(post_params)
if @post_save
redirect_to posts_path, :notice => "Post has benn created"
else
render "new"
end
end
def post_params
params.require(:post).permit(:title, :body, :category_id)
end
When I try to add another post via an html form nothing happens. The page with the form is reloaded and the post itself is not saved. What am I doing wrong?
Upvotes: 0
Views: 56
Reputation: 331
I think that you should also permit :author_id if you have such a field in your form. Because, as I understand, post belongs_to :author. That means author_id is mandatory in post creation. And also, you have a typo, you should change "@post_save" => "@post.save!" (it was mentioned in earlier answer).
Upvotes: 0
Reputation: 15045
That's because there's a typo in the create
method
@post_save
must be @post.save
def create
@post = Post.new(post_params)
if @post.save
redirect_to posts_path, :notice => "Post has been created"
else
render "new"
end
end
Since @post_save
is not defined, else
block is evaluated and new
page is rendered and nothing happens
Upvotes: 2