I am building an event app that lets users post events, and other users can 'register' themselves as attending that event. I currently have two models, 'User' and 'Article', where article is the event that a user can post. An article
has_many :articles, dependent: :destroy
You could try either a
has_many through: or a
has_and_belongs_to_many relationship. Personally, I think I would use a HABTM for this, but the advantage of a HM Through is that there is an intermediate model, which can be used for additional information (such as whether an "attendee" is going or merely interested, etc): http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association
As for having multiple different associations between the same two models, you can name the association anything you like but specify the class_name of the model you are pointing to: http://guides.rubyonrails.org/association_basics.html#has-and-belongs-to-many-association-reference
class Article < ActiveRecord::Base belongs_to :user has_and_belongs_to_many :attendees, class_name: "User", join_table: "articles_attendees", foreign_key: "attended_event_id", association_foreign_key: "attendee_id" ... end
And for your User model:
class User < ActiveRecord::Base has_many :articles has_and_belongs_to_many :attended_events, class_name: "Article", join_table: "articles_attendees", foreign_key: "attendee_id", association_foreign_key: "attended_event_id" ... end
That way you're able to name your association whatever you like, just be sure to keep your singulars singular and your plurals plural, and generally everything readable.
class_name should be the name of the model to which you are defining the relationship.
foreign_key is the database column name containing the ID of the models in which the relationship is defined. For example, in your User model,
foreign_key should be the user ID. The
association_foreign_key is the column containing the ID of the model to which you are linking.
Also don't forget to create your migration. Something like this example:
class CreateArticlesAttendees < ActiveRecord::Migration def self.up create_table :articles_attendees, :id => false do |t| t.references :attended_event t.references :attendee end add_index :articles_attendees, [:attended_event_id, :attendee_id] add_index :articles_attendees, :attendee_id end def self.down drop_table :articles_attendees end end