开发者

Create a model attribute from checkbox input

This creates and saves a new row to my database. The problem is that I have a checkbox in my view file for a boolean value, but no matter whether the box is checked or not, the new row is always false. I also can't get any of the other attributes to show up as anything other than nil. Any ideas?

This is my view is:

<%= form_for(@setting) do |s| %>
  <div class="field" >
    <%= s.label :my_setting_attribute %>
    <%= s.check_box(:my_setting_attribute) %>
  </div>

  <div class="actions">
    <%= s.submit "Submit" %>
  </div>
<% end %>

And my controller:

def new
  @setting = Setting.new
end

def create
  @setting = Setting.new(params[:setting])
  if @setting.save
    redirect_to :action => 'index', :id => @setting.id
  else
    redirect_to :action => 'error'
  end
end

I think I have my route file set correctly:

resources :settings do
  collection do
    get :index
    post 'settings/new'
    get 'sett开发者_JAVA百科ings/show'
  end
end

Here's the development log excerpt:

Started POST "/settings" for 10.7.94.191 at 2011-07-25 20:30:11 -0400
  Processing by SettingsController#create as HTML
  Parameters: {"utf8"=>"â", "authenticity_token"=>"xxxxxxxxxxx=", "setting"=>{"my_setting_attribute"=>"1", "other_setting_attribute"=>"hello"}, "commit"=>"Submit"}
ESC[1mESC[36mUser Load (0.1ms)ESC[0m  ESC[1mSELECT `users`.* FROM `users` WHERE `users`.`id` = 2 LIMIT 1ESC[0m
  ESC[1mESC[35mSQL (0.1ms)ESC[0m  BEGIN
  ESC[1mESC[36mSQL (1.0ms)ESC[0m  ESC[1mdescribe `settings`ESC[0m
  ESC[1mESC[35mAREL (0.3ms)ESC[0m  INSERT INTO `settings` (`facebook_token`, `twitter`, `user_id`, `created_at`, `updated_at`, `image_id`) VALUES (NULL, NULL, NULL, '2011-07-26 00:30:12', '2011-07-26 00:30:12', NULL)
ESC[1mESC[36mSQL (57.1ms)ESC[0m  ESC[1mCOMMITESC[0m
Redirected to http://3000/settings?id=12


May not be the "correct" way of doing it but you could probably do this:

In your controller for the update and create method, check what the value of params[:my_setting_attribute] is. You may need to conditionally set the attribute to either "true" or "false".

e.g. perhaps it is returning "1" instead of true (which your log seems to indicuate), then you can set it yourself with something like @my_object.my_setting_attribute = true if params[:my_setting_attribute] == "1". Then probably add an else clause to set everything else to false, just to be safe.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜