wyc
wyc

Reputation: 55293

Making boolean attribute false or true depending on which submit button the user clicks?

I added a draft attribute to my Post model:

  create_table "posts", :force => true do |t|
    t.text     "content",            :limit => 255
    t.integer  "user_id"
    t.boolean  "draft",                             :default => false
    t.datetime "published_at"
  end

Right now it appears as a checkbox:

<%= form_for(@post, :html => { :multipart => true }) do |f| %>

<%= f.label :title %>
<%= f.text_field :title %>

<%= f.label :content %>
<%= f.text_area :content, id: "wysihtml5-textarea" %>

<%= f.label :category_id, "Select Category" %>
<%= f.collection_select :category_id, Category.order(:name), :id, :name,
                        { prompt: 'Select Category' } %>

<%= f.label :draft %>
<%= f.check_box :draft %>

<div class="form-actions">
  <%= f.submit "Create post", class: "btn btn-primary" %>
</div>

<% end %>

I would like to modify the form so that instead of clicking the draft checkbox, the user can click either Save as Draft or Publish button (Like you do in WordPress).

I have no idea how to make those buttons influence the value of the draft attribute.

Any ideas?

Upvotes: 0

Views: 314

Answers (1)

Chowlett
Chowlett

Reputation: 46675

When you click a submit button, Rails will automatically include a "commit" entry in the params hash, which carries the text of the button clicked. You should be able to key off that in your controller.

Note that, last time I tried, there was a bug in jquery-ujs which meant this tactic didn't work for forms declared as :remote => true. However, that was a while ago and I did raise a bug report, so it may have been fixed subsequently.

Upvotes: 1

Related Questions