繁体   English   中英

如何从collection_select rails处理数组

[英]How to handle array from collection_select rails

我有一个使用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 .....

你能试一下吗:

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。

希望这可以帮助。 让我知道这是否适合您。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM