Hi,
I’m trying to wrap my head around an association problem.
create_table :events do |t|
t.column :name, :text
t.column :place, :text
end
create_table :users do |t|
t.column :name, :text
end
create_table :events_users do |t|
t.column :event_id, :integer
t.column :user_id, :integer
t.column :user_role, :text
end
I want to use :events_users as a HABTM table to connect :events
and :users like so:
class Event < ActiveRecord::Base
has_and_belongs_to_many :users
end
class User < ActiveRecord::Base
has_and_belongs_to_many :events
end
But I also want to be able to access the extra information of which
role the user had during an event. I can’t see how to do that.
has_many :through doesn’t seem to offer a solution either, or does it?
Best,
Dav
So I figure I might create a new class inheriting from User and add
some extra variables like:
class Participant < User
@role = …
end
But how can I populate a single extra variable this way?
Any suggestions please, still trying to figure Rails out…
Chrs,
Dav
On 6. Oct 2007, at 14:19, David Zentgraf wrote:
t.column :event_id, :integer
t.column :user_id, :integer
t.column :user_role, :text
end
I got my HABTM association between users and events going so far, I
can even retrieve the records from the database including the extra
information from the HABTM table.
event.users #=> <User @attributes={“name”=>“Dav”, “user_role”=>“Host”}
etc…
The user_role being selected with the rest of the user attributes
seems to be a side-effect of ActiveRecord selecting * from all tables
when retrieving HABTM associations. Good so far, but how can I get
the user_role value into the table? I guess I could specify a
custom :insert_sql string in the model, but that seems very messy and
additionally I wouldn’t know how to hand the attribute to ActiveRecord.
event.users.create(:name => “foo”, :user_role => “Guest”)
certainly wouldn’t work…
Any suggestions please!
Chrs,
Dav
You need to use has_many :through.
–
Michael W.
I see! It actually works now.
Thanks!