简体   繁体   English

如何从collection_select rails处理数组

[英]How to handle array from collection_select rails

I have a form that uses collection_select to be able to select multiple groups. 我有一个使用collection_select的表格,可以选择多个组。 But when I try to create a new record it fails in my notifications_controller.rb. 但是,当我尝试创建新记录时,它在我的notifications_controller.rb中失败。 The parameters are being passed correctly I think it might have to do with collection_select being passed as an array. 参数正确传递,我认为这可能与将collection_select作为数组传递有关。 I just can't for the life of me figure out how to handle it in the controller. 我只是一辈子都无法弄清楚如何在控制器中处理它。

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

What is being passed in the parameters: 参数中传递了什么:

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

schema.rb 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 new.html.erb

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

notifications_controller.rb 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 .....

Can you try: 你能试一下吗:

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

As you're selecting multiple groups and searching the group, you'll be getting an Array of the Groups. 当您选择多个组并搜索该组时,将得到一个“组Array ”。 Instead when using the where as above, you'll get a ActiveRecordRelation 相反,当使用上述where时,您将获得ActiveRecordRelation

You've to loop through this result and use the users association with each record. 您必须遍历此结果,并对每个记录使用users关联。

Note : The associations don't work with Active Record Relations or Arrays. 注意associations不适用于Active Record Relations或Arrays。

Hope this helps. 希望这可以帮助。 Let me know if this works for you. 让我知道这是否适合您。

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

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