Skip to content

Instantly share code, notes, and snippets.

@simonreed
Created February 12, 2016 09:53
Show Gist options
  • Save simonreed/c601bf75c58d08ebd2ee to your computer and use it in GitHub Desktop.
Save simonreed/c601bf75c58d08ebd2ee to your computer and use it in GitHub Desktop.
Using HABTM with a join table.
<%# This will show a list of check_boxes for each service, if the staff has already enabled a service then it will show as checked %>
<%= f.collection_check_boxes(:services_ids, Service.all, :id, :to_s) %>
# Use rails g migration add_staffs_services_join_table to create this file with the correct filename
class AddStaffsServicesJoinTable < ActiveRecord::Migration
def change
create_join_table :staffs, :services do |t|
t.index :staff_id
t.index :service_id
end
end
end
class Service < ActiveRecord::Base
has_and_belongs_to_many :staffs, join_table: 'staffs_services'
end
class Staff < ActiveRecord::Base
has_and_belongs_to_many :services, join_table: 'staffs_services'
end
class StaffsController < ApplicationController
def show
@services = @staff.services
end
# Remember to add whitelist the service_ids param in the controller if using Rails 4.
# You'll need to set it to default to an array as it's a join_table attribute.
# This is only needed if you're going to actually edit the association in the form,
# i'm not sure if you want to be able to do that on both staff and services or not.
def staff_params
params.require(:staff).permit(service_ids: [])
end
end
@chrismahon
Copy link

Ok cheers dude

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment