Question

Morning, I have 3 Models - User, Events & Checkin

User may be either an attendee or co-speaker. The relationship/collection join works. However whenever I create an Event; it automatically adds them to co-speaker array. In my create method it should only add them to attendee array.

Calling @event.attendees gives me current_user which is correct, however it returns the same for @event.cospeaker which it shouldn't.

user.rb

has_many :checkins
has_many :events, :through => :checkins

checkin.rb

belongs_to :user
belongs_to :event

event.rb

has_many :checkins
has_many :attendees, :through => :checkins, :source => :user
has_many :cospeakers, :through => :checkins, :source => :user
belongs_to :owner, :class_name => "User"

Event Controller

def create
@event = current_user.events.build(params[:event])
 if @event.save
     @event.owner = current_user

     @event.attendees << current_user
     @event.save
    redirect_to checkin_event_path(:id => @event.id)
 end
end
Was it helpful?

Solution

Your problem is here:

has_many :attendees, :through => :checkins, :source => :user
has_many :cospeakers, :through => :checkins, :source => :user

The has_many through: is the same as has_and_belongs_to_may, it's just the linking table has a custom name. You're essentially saying "event attendees are any user that is in the checkins table" and "event cospeakers are any user that is in the checkins table". You can see why that will return the same result.

What you need to do is add a flag to the checkins table and then add a condition to the has_many through:. Assuming you add a "is_cospeaker" boolean to the checkins table, you can do this:

has_many :attendees, through: :checkins, source: :user, conditions: {is_cospeaker: false}
has_many :cospeakers, through: :checkins, source: :user, conditions: {is_cospeaker: true}

(Note, that's Ruby 1.9+ hash syntax. Hopefully, you are using Ruby 1.9 or 2.0)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top