Stoob
Stoob

Reputation: 121

Creating new associations after multiple checkboxes ticked

I have a 'service' model which is constant and has an 'id' column and a 'service_type' column.

'service' belong_to_and_has_many 'profiles'

When creating their profile a user can choose which services they provide via multiple choice check boxes.

On submission I want to add the services to the users profile.

Currently I'm tying to do this by using the values of the array of 'services' from the service params and trying to loop over the array in the controller adding association for each elements value in the array, suffice to say its a bit of a mess and not working and I need help trying to make it work.

Controller:

def create
@profile = Profile.new(profile_params)

if @profile.save 
    add = []
    types = params(:services)
    types.each do |service|
    p = Service.where('service_type LIKE ?', '%#{service}%')
    add << p
   self.services << add
  end 

  redirect_to '/' 

else
  render '/profiles'
end
end

def profile_params
params.require(:profile).permit(:bio, :services, london_attributes: [:id, :south, :north, :east, :west, :central])

end

View: - each ="name" is the same as a 'service_type' in the 'service' model:

<h3>Please click the services you provide</h3>

      <div class="checkbox">
        <label> <input type="checkbox" name="profile[services][]" value="handyman">Handyman</label>
      </div>

      <div class="checkbox">
        <label> <input type="checkbox" name="profile[services][]" value="plumber">Plumber</label>
      </div>

Params with token an other params removed:

Parameters: "profile"=>{
  "bio"=>"",
  "services"=>
    ["handyman", "plumber"]}}
Unpermitted parameter: services

profile.rb:

class Profile < ActiveRecord::Base
  belongs_to :user
  has_and_belongs_to_many :places
  has_and_belongs_to_many :services
  accepts_nested_attributes_for :places
  accepts_nested_attributes_for :services
  has_one :london
  accepts_nested_attributes_for :london

Upvotes: 1

Views: 84

Answers (1)

Pavan
Pavan

Reputation: 33542

Unpermitted parameter: services

You should change :services to :service_ids => [] in profile_params

def profile_params
  params.require(:profile).permit(:bio, :service_ids => [], london_attributes: [:id, :south, :north, :east, :west, :central])
end

And use collection_check_boxes to generate the check boxes.

<%= f.collection_check_boxes(:service_ids, Service.all, :id, :name) %>

Also change the create method to below

def create
@profile = Profile.new(profile_params)

if @profile.save 
  redirect_to '/' 
else
  render '/profiles'
end
end

Upvotes: 1

Related Questions