我有一个使用 collection_select 能够选择多个组的表单。但是当我尝试创建新记录时,它在我的通知控制器.rb 中失败了。参数被正确传递我认为这可能与 collection_select 作为数组传递有关。我一生都无法弄清楚如何在控制器中处理它。
undefined method `users' for #<Array:0x007fbb0e891b58>
参数中传递的内容:
"group"=>{"group_id"=>["1", "2"]},
模式文件
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
新的.html.erb
<%= f.label :To %>
<%= collection_select(:group, :group_id, Group.all,:id,:name,
{include_hidden: false}, {:multiple => true})%>
通知_控制器.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 关系或数组。
希望这可以帮助。让我知道这是否适合您。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句