Jacek717 Jacek717 - 3 years ago 83
Ruby Question

ruby on rails cannot use permit.require

Im tring 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 by html form nothing happen. Page with the form is reloaded and post itself is not saved. What am I doing wrong?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download