Meltemi
Meltemi

Reputation: 38359

Rails: pull value from has_many :through relationship in model

User   
  has_many :reservations, :dependent => :destroy
  has_many :events, :through => :reservations

Reservation
  belongs_to :user
  belongs_to :event

Event
  has_many :reservations, :dependent => :destroy
  has_many :attendees, :through => :reservations, :source => :user

What I want is a method on User that I can query to find out the status of that user at a given event. Something like:

  def attendee_status(event)
    res = self.reservations.where(event: event.id).first
    if res
      res.status
    else
      0
    end
  end

I'm confused by the association syntax, among other things...column reservations.event does not exist

each user should only have one reservation for any particular event...first assumes that. (better way?)

anyway, the status method on Reservation model should return one of %w[not_attending, awaiting_payment, payment_received]

what's the "Rails way" to handle these relationship/look-ups from model to model (perhaps even starting with a clearer method name: attendee_status(event))?!?

Upvotes: 0

Views: 154

Answers (1)

Geoff
Geoff

Reputation: 2228

User.reservations is a collection and User.events is a collection. Because your through association is linked via a belongs_to then both collections are the same size (assuming all reservations have an event).

User.reservations.event does not exist, but User.reservations.first.event will (assuming there is at least one reservation).

The first call is the function Reservation::event on the class, and the second is Reservation#event on an instance of the class. Calling Reservation::first on a collection gives you back an instance.

I think you just need to fix this line like so:

res = self.reservations.where(event_id: event.id)

I hope that helps.

Upvotes: 1

Related Questions