如何使用ROR获取collection_select标记的参数

时间:2018-06-14 18:23:36

标签: arrays ruby select ruby-on-rails-5

我有一个rails应用程序,其中我有一个多选框

 = section.collection_select(:room_ids, @rooms, :id, :location, {prompt:false}, {multiple: true, class: 'form-control list2' , required: true })
 = section.submit "", class: "save-btn"

在我的部分控制器中,我想创建一个包含从选择框

中选择的所有多个项目的数组

我正在尝试像

这样的东西
    class SectionsController < InheritedResources::Base
  respond_to :html,:js
  before_action :get_rooms, only: [:edit,:new]

  def create
      room_ids = params[:room_ids]
      if room_ids.count > 20
        flash[:error] = "Too many rooms selected"
        redirect_to sections_path
      else
        create! { sections_path }
      end
  end

  def update
    update! { sections_path }
  end

  protected

  def permitted_params
    params.permit(section: [:name, :section_time, :credits, room_ids: []])
  end

  def get_rooms
    @unassigned_rooms = Room.left_outer_joins(:section).where("rooms.section_id IS ?", nil).order('rooms.location asc').all.map{ |room| [ room.location, room.id, { credit: room.credit } ] }
    @rooms = @section.rooms
  end

end

但这不起作用,并给我一个错误,说

undefined local variable or method `room_id' for #<SectionsController:0x007fc4ca7808c0> Did you mean? room_url

我尝试将collection_select的名称更改为room_ids[],但这对我说错误没有帮助

wrong number of arguments (given 0, expected 1..2)

我基本上尝试做的是用户创建多个房间的部分,通过从选择框中选择房间,但用户每个部分只能分配20个房间

任何人都可以告诉我我做错了什么或者我可以尝试的其他替代方案吗?

1 个答案:

答案 0 :(得分:0)

您正在使用room_id[] = ...

创建意外的字段名称

你应该做......

room_ids = params[:room_ids]
if room_ids.count > 20