_1oejq
Last Updated: February 25, 2016
·
10.57K
· himself
Logo

Handling has_and_belongs_to_many checkboxes with Rails 4 strong_parameters

We are not allowed to use attraccessible in Rails 4 anymore, now the way to get parameters from our create and update forms is through ** strongparams **.

// In the Restaurant model
class Restaurant < ActiveRecord::Base
    has_and_belongs_to_many :cuisines
end

// In the restaurant_controller
def restaurant_params
  params[:restaurant].permit(
    :name,
    :address,
    :phone,
    {:cuisine_ids => []}
  ),
end

This way when we call params to our restaurant create and update methods we pass them the restaurant_params function.

Rails automatically handles the insert and update of our related models, in this case Cuisine if we pass a cuisine_ids array containing the ids of the Cuisine instances.

Using strongparameters we need to define that cuisineids is an array.

{ 
    :cuisine_ids => [] 
}

References

Strong Parameters on Github

RailsCasts #17 HABTM Checkboxes

Say Thanks
Respond

6 Responses
Add your response

8356

Thanks, had trouble figuring this one out.

over 1 year ago ·
8725

Wonderful! Thanks for the tip.

over 1 year ago ·
12920
27b139984d9ce18d278ad124edf7a738

Thanks!

over 1 year ago ·
13424
A00ec595345c97c0f0295576a62f2e0e

many thanks!

over 1 year ago ·
15740
D5bc3d5d95497410ae5775079b1b9d15

This is just the exact solution for my problem! Thank you!

over 1 year ago ·
16389
Mug shot 200x200

I recently found this helper that can be used to generate the checkboxes: http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_check_boxes

over 1 year ago ·