![](/img/trans.png)
[英]how to pass multiple ids as an array in form 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.