Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 - checkbox for create (opposite of _destroy)

I have a Query model with a has_many relationship to OutputFields. In my query controller's new function I build several OutputFields within the query instance. In my form, I want each checkbox to determine whether the object is saved (a check means save this instance of OutputField to the database). How can I do this?

my models:

class Query < ActiveRecord::Base
  attr_accessible :description, :name

  has_many :output_fields, :dependent => :destroy
  accepts_nested_attributes_for :output_fields
end

class OutputField < ActiveRecord::Base
  attr_accessible :query_id, :column_name, :table_name

  belongs_to :query
end

relevant sections of my queries controller. Structure is another model.

  # GET /queries/new
  # GET /queries/new.json
  def new
    @query = Query.new
    Structure.columns.each do |column|
      @query.output_fields.build( :table_name => Structure.table_name, :column_name => column.name )
    end

    respond_to do |format|
      format.html # new.html.erb
      format.json { render :json => @query }
    end
  end

Finally, my view. Right now I'm linking the checkbox to the destroy attribute, which I think will do the exact opposite of what I want.

<%= form_for(@query) do |f| %>
  <%= f.fields_for :output_fields do |builder| %>
    <div class="field">
      <%= builder.check_box :_destroy %>
      <%= builder.label :_destroy, builder.object.column_name %>
    </div>
  <% end %>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

If it's not obvious, I'm trying generate a user interface for a simple query builder. This is my first rails app, so any advice is appreciated.

like image 925
TimmyJ Avatar asked May 03 '13 16:05

TimmyJ


1 Answers

By default the value of the check_box form helper is to set the checked_value to '1' and the unchecked_value to '0'. So to reverse the behaviour of the destroy checkbox, just switch these values around.

<%= builder.check_box :_destroy, {}, '0', '1' %>
like image 195
Michael MacDonald Avatar answered Dec 10 '22 07:12

Michael MacDonald