Last Updated: February 25, 2016
· himself

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

// In the restaurant_controller
def restaurant_params
    {:cuisine_ids => []}

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 => [] 


Strong Parameters on Github

RailsCasts #17 HABTM Checkboxes

6 Responses
Add your response

Thanks, had trouble figuring this one out.

over 1 year ago ·

Wonderful! Thanks for the tip.

over 1 year ago ·


over 1 year ago ·

many thanks!

over 1 year ago ·

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

over 1 year ago ·

I recently found this helper that can be used to generate the checkboxes:

over 1 year ago ·