I have two models Site and User. When a user registers with the app they choose a site to belong to. So a site has_many :users and a user belongs_to :site.
app\models\site.rb
class Site < ActiveRecord::Base
has_many :users
end
app\models\user.rb
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable
belongs_to :site
has_and_belongs_to_many :roles, :uniq => true
end
This really reflects a user’s home site and I often call the relationship to find out where the user is from, for instance:
<%= user.lastname %>, <%= user.firstname %> from Site: <%= user.site.name %>
which translates to:
Smith, John from Site: GenericCo Operations
I would like to add a habtm relationship where users can SUPPORT many sites, so a user would be able to choose which sites they support from check boxes listing the sites.
I am familiar with the habtm relationship because my users have and belong to many roles. I established this as
has_and_belongs_to_many :roles, :uniq => true
I know for a fact that if I add a join table and use
has_and_belongs_to_many :sites
on my model everything will go crazy with tons of errors. I would appreciate any helpful advice and code hints.
The first argument to habtm is the name of the method you’ll call to get the collection. It can be anything you want, so long as you specify the model class with :class_name
Depending on how you name things in your database, you might also need to specify :join_table, :foreign_key, or :association_foreign_key. Take a look at the Options section of http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many for more info.