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 => []}
  ),
endThis 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
Written by Wilbur Suero
Related protips
6 Responses
Thanks, had trouble figuring this one out.
Wonderful! Thanks for the tip.
 
Thanks!
 
many thanks!
 
This is just the exact solution for my problem! Thank you!
 
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

 
 
 
 
