Strange error using association methods


#1

Hi,

I’ve recently replaced a rather clunky old piece of code:

user = User.find(id)
meeting_attendees = user.meetings.map { |m| m.id }
meetings = Meeting.find(:all, :include =>
[:users, :groups], :conditions => [‘meetings.date_and_time > ? and
meetings.id in(?)’, Time.now, meetings_attendees])

with

user.meetings.find(:all, :conditions => ['meetings.date_and_time

?’, Time.now])

I’m having a strange error whereby an attribute called “status” in
the resulting list of meetings is being set to ‘0’, but not for every
meeting record. Just randomly (although it’s the same records each
time). Now the problem appears to be that because the join table also
has a “status” attribute (the status of each individual attendee
rather than the actual event status) that the call is getting
confused in some way.

Will I need to write my own association extension to resolve this (or
indeed just rewind to the original code)?

Kind regards,
Steven


#2

Steven,

If the user has_and_belongs_to_many :meetings then the status
attribute will be automatically injected into the objects returned
because you’re accessing the objects through the association.

The value of status is being read from the model’s table and then
clobbered by the value from the join table. You could rename the
status columns so that they don’t collide.

See:
http://api.rubyonrails.com/classes/ActiveRecord/Associations/ClassMethods.html#M000467
for more details.

You also don’t need the ‘meetings’ in the conditions:

user.meetings.find_all_for_date_and_time(:all, :conditions =>
['date_and_time

?’, Time.now])

Hope this helps.

Cody