robb
robb

Reputation: 294

Changing boolean values on f.submit (Rails)

I have an edit form in which I want users to click a button to post a story or another button to save as a draft. This is what I have so far:

<%= f.submit "Save Draft", params: {draft: true}, class: "btn btn-default" %>
<%= f.submit "Publish", params: {draft: false}, class: "btn btn-default" %>

If I use a checkbox, it works. Any clues?

Upvotes: 0

Views: 412

Answers (1)

trh
trh

Reputation: 7339

If you take a look at the raw params of your update you'll probably see why this isn't working. The submit button's attribute and information is outside of the params hash, and nothing you can pass it will change that.

Now when you use a checkbox, obviously that's inside the params hash just as any normal field would.

Personally I would set the parameter in the controller when your params are checked / whitelisted.

e.g.

def post_params
  if params[:draft]
    return params.require(:post).permit(:name, :body).merge(draft: true)
  else
    return params.require(:post).permit(:name, :body).merge(draft: false)
  end
end

Then in your form, add a name tag to your Draft submit button

<%= f.submit "Save Draft", name: draft, class: "btn btn-default" %>
<%= f.submit "Publish", class: "btn btn-default" %>

Which would produce something like:

{"utf8"=>"✓", "_method"=>"patch", "authenticity_token"=>"abcdefghijklmnopqrstuvwxyzg==", "post"=>{"name"=>"some title", "body"=>"some post body"}, "draft"=>"Save Draft", "controller"=>"posts", "action"=>"update", "id"=>"1"}

And your params will be set for your because the draft attribute was found.

Upvotes: 1

Related Questions