Created
February 12, 2016 09:53
-
-
Save simonreed/c601bf75c58d08ebd2ee to your computer and use it in GitHub Desktop.
Using HABTM with a join table.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<%# 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) %> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Service < ActiveRecord::Base | |
has_and_belongs_to_many :staffs, join_table: 'staffs_services' | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Staff < ActiveRecord::Base | |
has_and_belongs_to_many :services, join_table: 'staffs_services' | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ok cheers dude