I have a form that uses collection_select to be able to select multiple groups. But when I try to create a new record it fails in my notifications_controller.rb. The parameters are being passed correctly I think it might have to do with collection_select being passed as an array. 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
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 .....
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. Instead when using the where
as above, you'll get a ActiveRecordRelation
You've to loop through this result and use the users
association with each record.
Note : The associations
don't work with Active Record Relations or Arrays.
Hope this helps. Let me know if this works for you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.