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
@simonreed
Copy link
Author

Hey dude, so these are obviously not in order. You'll want to create the migration first.

Note, these are for if you want to just associate a Staff with a Service with no other meta data. If say you want to be able to store, when a Staff/Service was connected, it's state or what have you then we'll need something a little different so let me know if that is what you want.

@chrismahon
Copy link

Hey dude cheers for this. I think I might need something a little different in that case as I need to be able to store what the price is for each Staff/Service, example being one staff member might charge £20 for Service whilst another charges £10.

I assume HABTM isn't appropriate in this case?

@simonreed
Copy link
Author

No let me create another gist to show you what you need for that.

@chrismahon
Copy link

Ok cheers dude

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