rohaldb rohaldb - 6 months ago 8x
Ruby Question

Having different associations between two models Rails

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

belongs_to :user
and a user
has_many :articles, dependent: :destroy

I am trying to set up a new database to store which users plan to attend an event, in the form of a 'Registration', where it stores a user and the event he plans to attend. This means i need a many to many association between Users and Articles (as a user can attend multiple events, and an event can have multiple attendees). But will this not conflict with the original setting that states an article belongs to a single user?

How do i set this up so my associations dont interfere?


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):

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:

For example:

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"

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"

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
    add_index :articles_attendees, [:attended_event_id, :attendee_id]
    add_index :articles_attendees, :attendee_id

  def self.down
    drop_table :articles_attendees