0

I'm using the form_for collection_select method, with multiple set as true. When i submit the form, the receiver_id is being set as an array value inside the hash, as a result i get an error saying receiver_id cannot be blank as this is not being passed in the create action.

i think i need to convert the array value to a string so it can be passed in the create action?

my code looks like this:

<%= 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

the params has looks like this

Parameters: {"utf8"=>"✓",
 "authenticity_token"=>"e36oB6gr0GYbCb3kwfuDJwP0alPxed7U2mD/FlTu8AY=",
 "message"=>{"body"=>"sdfsdfsdf", "receiver_id"=>["1"]}, "commit"=>"Send"}
AngocA
  • 7,655
  • 6
  • 39
  • 55
  • possible duplicate of [Rails has\_many :through and collection\_select with multiple](http://stackoverflow.com/questions/8239961/rails-has-many-through-and-collection-select-with-multiple) – phoet Feb 08 '14 at 21:30

1 Answers1

0

after some more digging around i've found the following method works, i dont know if this is optimal or if there is a neater way of doing it but it's working fine at the moment.

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

credit to this video on youtube for the idea: http://www.youtube.com/watch?v=ZNrNGTe2Zqk