【问题标题】:How to get value from checkbox in rails如何从rails中的复选框中获取价值
【发布时间】:2015-08-15 10:15:35
【问题描述】:

我在 rails 中使用 simple_form,我将其作为复选框:

<%= f.input :delivery_days, as: :check_boxes,
    collection: [
      'Sunday',
      'Monday',
      'Tuesday',
      'Wednesday',
      'Thursday',
      'Friday',
      'Satusday',
      'All'],
      wrapper: :vertical_radio_and_checkboxes 
%>

我无法在我的控制器中获取选定复选框的值。

我正在使用以下代码来获取它:

def user_basic_params
    logger.info "from user_basic_params"
    params.require(:profile).permit(:delivery_days[])
end

我还有其他表单字段,但它们得到了正确处理,并且我能够获取它们的值。

控制台输出是:

Started POST "/profiles" for 127.0.0.1 at 2015-06-02 02:07:56 +0530
Processing by ProfilesController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"w3RvztJtKq56qimpZPj3KD9S5pr1vbw2K6b7eToaEV5rEuBsx1jqJ8gITg+uHq8TgBoeYZPsczQLghWg2fhpCg==", "profile"=>{"milk_animal"=>"Any", "milk_type"=>"Any", "brand"=>"Amul", "time_of_delivery(1i)"=>"2015", "time_of_delivery(2i)"=>"6", "time_of_delivery(3i)"=>"1", "time_of_delivery(4i)"=>"20", "time_of_delivery(5i)"=>"37", "start_date(1i)"=>"2015", "start_date(2i)"=>"6", "start_date(3i)"=>"1", "delivery_days"=>["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Satusday", "All", ""], "name"=>"Sony", "address"=>"asdfghjk", "pincode"=>"zxcvbnm,", "contact_no"=>"2345678"}, "commit"=>"Create Profile"}
from create
from user_basic_params
Completed 500 Internal Server Error in 1ms (ActiveRecord: 0.0ms)

ArgumentError (wrong number of arguments (0 for 1..2)):
  app/controllers/profiles_controller.rb:53:in `[]'
  app/controllers/profiles_controller.rb:53:in `user_basic_params'
  app/controllers/profiles_controller.rb:18:in `create'

【问题讨论】:

  • 请显示控制台日志.......
  • 使用控制台输出更新

标签: ruby-on-rails ruby-on-rails-4


【解决方案1】:

问题出在代码的permit(:delivery_days[]) 部分。 Rails 期望括号包含 1 或 2 个参数,但您没有传递任何参数,从而引发错误。 我不确定括号为什么在那里,尝试删除它们,我相信你的代码应该可以工作。

【讨论】:

  • 这个线程上的 cmets 如何帮助我 stackoverflow.com/questions/17982904/…
  • 在这种情况下,您缺少将其变为哈希的 => 部分。 :delivery_days[] 尝试将 :delivery_days 作为数组访问而不给出偏移量,而 :delivery_days =&gt; [] 将其定义为带有空数组的散列。
【解决方案2】:

替换这个

params.require(:profile).permit(:delivery_days[])

params.require(:profile).permit(:delivery_days)

【讨论】:

    猜你喜欢
    • 2018-07-24
    • 2013-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-08
    • 2020-06-02
    • 1970-01-01
    相关资源
    最近更新 更多