vendredi 7 avril 2017

How to change method name for has_through rails association?

I am trying to create two has many relations to the same destination tables but I am unable to override the default method name rails creates when defining the association.

The following is the case:

class User < ApplicationRecord
  has_many :conference_attendees, dependent: :destroy
  has_many :conference_organizers, dependent: :destroy
  has_many :conferences, through: :conference_attendees, class_name: 'attending', dependent: :destroy
  has_many :conferences, through: :conference_organizers, source: :conference, dependent: :destroy

class ConferenceOrganizer < ApplicationRecord
  alias_attribute :organizers, :users
  belongs_to :conference
  belongs_to :user
end

class ConferenceAttendee < ApplicationRecord
  belongs_to :conference
  belongs_to :user
end

class Conference < ApplicationRecord
  has_many :conference_attendees, dependent: :destroy
  has_many :conference_organizers, dependent: :destroy
  has_many :users, through: :conference_attendees, dependent: :destroy
  has_many :organizers, through: :conference_organizers, source: :user, dependent: :destroy

I am trying to access all the conferences that a user attended and then all conferences that a user organized using something like following:

User.find(id: <id>).organizing
User.find(id: <id>).attending

but I am unable to and

User.find(id: <id>).conferences

defaults to organizing conferences. How do I access attending conferences?

Aucun commentaire:

Enregistrer un commentaire