Problems with getting firstname from user in habtm relationship

Hey there..

In my view i have:

<%= @event.invited %>

In my event.rb I have:

class Event < ActiveRecord::Base
  has_and_belongs_to_many :users

  def invited
    users.compact.join(", ")
  end
end

In my users.rb I have:

class User < ActiveRecord::Base
  has_and_belongs_to_many :events
end

The output I get in my view, when calling @event.invited is: #, #

My question is, how do I get it to output the names of the users,
instead of just the # .. I have tried doing a:

for user in users do
  user.first_name
end

But that outputs # #

What am I doing wrong?

Thank you soo much in advance!
-Jesper

Jesper,

Looking at the info you provided, there's nothing which actually
retrieves something from the database.

Lets say you've done:

@event = Event.find(:all)

then with your model as is you can refer to then do:

invited = @event.users (assuming that merely the presence of a
relationship between an event and a user means they're invited).

if you're only after the name then you could do:

invited = @event.users.collect! {|u| u.name}.join(',')

You might also changing your model to a :has_many :though approach
which lets you easily store attributed in the join table which, for
event management, would be very appropriate. Then you can have a
status code in the join table like "invited", "accepted", "scumbag
didn't show", "spam with many offers" or whatever you want.

If you follow this approach then your model would be something like:

class Event
:has_many :event_records
:has_many :users, :though => :event_records

In your controller
@invited = @event.users.find(:conditions => "event_records.status =
'invited'")

And in your view
<% for invited in @invited %>
    <%= invited.name %>
<% end %>

Hope this helps (at least a little)

Cheers, --Kip