如何从collection_select rails处理数组

时间:2017-11-20 02:56:16

标签: ruby-on-rails ruby postgresql

我有一个使用collection_select的表单,可以选择多个组。但是当我尝试创建一个新记录时,它在notifications_controller.rb中失败了。参数正确传递我认为它可能与collection_select作为数组传递有关。我只是不能为我的生活弄清楚如何在控制器中处理它。

 undefined method `users' for #<Array:0x007fbb0e891b58>

参数中传递了什么:

 "group"=>{"group_id"=>["1", "2"]},

schema.rb

create_table "notifications", force: :cascade do |t|
 t.string "title"
 t.string "first_name"


 end

create_table "notifications_users", id: false, force: :cascade do |t|
 t.bigint "user_id", null: false
 t.bigint "notification_id", null: false
 end

create_table "users", force: :cascade do |t|
 t.string "first_name"
 t.string "last_name"
 t.string "user_type"
 t.string "username"


end

new.html.erb

   <%= f.label :To %>
       <%= collection_select(:group, :group_id, Group.all,:id,:name, 
        {include_hidden: false}, {:multiple => true})%>

notifications_controller.rb

def create

@notification = Notification.new(notification_params)


if @notification.save
  @group = Group.find(params[:group][:group_id])

  #raise @group.inspect

  @users = @group.users <--this is where it fails   
  @users.each do |user|
  @notification.users << user
end .....

1 个答案:

答案 0 :(得分:0)

你可以尝试:

def create

  @notification = Notification.new(notification_params)

  if @notification.save
    @group = Group.where(id: params[:group][:group_id])

    @group.each do |group|
      @users = group.users <--this is where it fails   
      @users.each do |user|
      @notification.users << user
    end
  end
end

当您选择多个群组并搜索群组时,您将获得Array群组。相反,当您使用上述where时,您将获得ActiveRecordRelation

您必须循环显示此结果并对每条记录使用users关联。

注意associations无法使用Active Record Relations或Arrays。

希望这会有所帮助。如果这对您有用,请告诉我。