2

I need to submit and save some data. I need some post IDs from a form:

def message_post_collection_params
    params.require(:message_post).permit(
      { post_ids: [] }
    )
end

How can I take the IDs by button_to? My code:

button_to('Submit', approve_collection_message_posts_path, params: { message_post: { post_ids: ['1', '2'] } }, data: { config: 'Are you sure?', remote: true })

But it thows an error:

undefined method `permit' for #<String:0x007ffbdf9f1540>

on line params.require(:message_post).permit(.

How can I fix that?

jjjfff
  • 99
  • 6

2 Answers2

0

The reason I down voted Mike K's answer is because the declaration of the params does not appear to be the issue:

enter image description here

I believe the issue will be in how you're assigning params in the button_to:

button_to 'Submit', approve_collection_message_posts_path, params: { message_post: { post_ids: ['1', '2'] } }, data: { config: 'Are you sure?', remote: true }

enter image description here

Notice: <input type="hidden" name="message_post" value="post_ids%5B%5D=1&amp;post_ids%5B%5D=2" />

This is why you're getting your error (there is no nesting in your array) -- your params literally look like: "message_post" => "post_ids%5B%5D=1&amp;post_ids%5B%5D=2"


Fix

There is a cheap way to fix it:

def message_post_collection_params
   params.permit(post_ids:[])
end

= button_to 'Submit',  path_helper, params: { post_ids: ["1","2"] }, data: { config: 'Are you sure?', remote: true }

enter image description here

--

If you wanted to retain your nesting, you could use the following comment:

Note that the params option currently don't allow nested hashes. Example: params: {user: {active: false}} is not allowed. You can bypass this using the uglyparams: {:"user[active]" => true}

params: {:"message_post[post_ids]" => ["1","2"]}

enter image description here

Community
  • 1
  • 1
Richard Peck
  • 76,116
  • 9
  • 93
  • 147
-1

This should work: { :message_post => { post_ids: ['1', '2'] } }

Here's an example of it in rails console:

2.2.3 :017 > params = { :message_post => { post_ids: ['1', '2'] } }
 => {:message_post=>{:post_ids=>["1", "2"]}} 
2.2.3 :018 > parameters = ActionController::Parameters.new(params)
 => {"message_post"=>{"post_ids"=>["1", "2"]}} 
2.2.3 :019 > parameters.require(:message_post).permit(
2.2.3 :020 > { post_ids: [] })
 => {"post_ids"=>["1", "2"]} 
Mike K.
  • 3,751
  • 28
  • 41