Jl Smith wrote:
I’ve got an association question, involving a Ticket model and a User
model. My ticket model has integer fields, among others, called
opened_by and created_by, linking to user id’s. So basically, how do I
make that association so I can access the user fields in my ticket
views? Thanks in advance for any help!
This is what I have so far:
Ticket belongs_to :user, :foreign_key => “created_by”
Ticket belongs_to :user, :foreign_key => “opened_by”
User has_many :tickets
In my view, I want to do this:
<%=h @ticket.opened_by.username %>
You are using the name :user twice to create associations. That is the
name of the associations, and must be unique within the class. Also, you
need to differentiate the kinds of tickets a user may have. You want to
do something like this:
class Ticket < ActiveRecord::Base
belongs_to :creator, :class_name => “User”, :foreign_key =>
“creator_id”
belongs_to :opener, :class_name => “User”, :foreign_key => “opener_id”
end
class User < ActiveRecord::Base
has_many :created_tickets, :class_name => “Ticket”, :foreign_key =>
“creator_id”
has_many :opened_tickets, :class_name => “Ticket”, :foreign_key =>
“opener_id”
end
I changed the foreign key names to follow the Rails convention of using
_id. In Rails 2.0, the belongs_to method will change so that the
association name will imply the name of the foreign key instead of the
name of the class, so this will set you up for that eventual change.
–
Josh S.
http://blog.hasmanythrough.com/