我正在使用form_for collection_select方法,其中多个设置为true。 当我提交表单时,receiver_id被设置为散列内的数组值,因此我得到一个错误,说receiver_id不能为空,因为这不会在create动作中传递。
我想我需要将数组值转换为字符串,以便可以在create action中传递它?
我的代码如下:
<%= f.collection_select :receiver_id, receivers, :id, :email, {include_hidden: false, include_blank: true}, {class: 'form-control', multiple: true} %>
def message_params
params[:message].permit(:body, { receiver_id: [] })
end
def create
@message = current_user.messages.create(message_params)
end
params看起来像这样
Parameters: {"utf8"=>"✓",
"authenticity_token"=>"e36oB6gr0GYbCb3kwfuDJwP0alPxed7U2mD/FlTu8AY=",
"message"=>{"body"=>"sdfsdfsdf", "receiver_id"=>["1"]}, "commit"=>"Send"}
答案 0 :(得分:0)
def create
message_params[:receiver_id].each do |message|
if !message.empty?
@message = current_user.messages.create(body: message_params[:body], receiver_id: message)
end
end
respond_with message, location: messages_url
end
在youtube上对此视频赞不绝口:http://www.youtube.com/watch?v=ZNrNGTe2Zqk