从复选框输入创建模型属性

时间:2011-07-26 00:41:10

标签: ruby-on-rails ruby-on-rails-3

这会创建一个新行并将其保存到我的数据库中。问题是我的视图文件中有一个复选框,表示布尔值,但无论是否选中该框,新行始终为false。我也无法将任何其他属性显示为除了nil以外的任何其他属性。有什么想法吗?

这是我的观点:

<%= 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 %>

我的控制员:

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

我想我的路线文件设置正确:

resources :settings do
  collection do
    get :index
    post 'settings/new'
    get 'settings/show'
  end
end

这是开发日志摘录:

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

1 个答案:

答案 0 :(得分:0)

可能不是&#34;正确&#34;这样做的方法,但你可能会这样做:

updatecreate方法的控制器中,检查params[:my_setting_attribute]的值是多少。您可能需要有条件地将属性设置为&#34; true&#34;或&#34; false&#34;。

e.g。也许它正在回归&#34; 1&#34;而不是真(你的日志似乎表明),那么你可以用@my_object.my_setting_attribute = true if params[:my_setting_attribute] == "1"之类的东西自己设置它。然后可能添加一个else子句将其他所有内容设置为false,只是为了安全。