views:

35

answers:

1

Hi, all.

I have 3 classes:

class User < ActiveRecord::Base
  has_many :events, :foreign_key => 'owner_id'
end

class Event < ActiveRecord::Base
  belongs_to :owner, :class_name => 'User', :foreign_key => 'owner_id'
end

class Event::User < Event

end

Class Event have 'type' field, and work as STI. Now i create Event:

Event::User.create(:owner => User.first)

=> #<Event::User id: 8, owner_id: 1, title: nil, type: "Event::User", created_at: "2010-07-05 00:07:32", updated_at: "2010-07-05 00:07:32">

And now i want to receive the owner of creating event, but receive:

Event.last.owner

=> #<Event::User id: 1, owner_id: 1, title: nil, type: "Event::User", created_at: "2010-07-04 23:28:31", updated_at: "2010-07-04 23:28:31">

SQL log has given me the following:

Event::User Load (0.4ms)   SELECT * FROM "events" WHERE ("events"."id" = 1) AND ( ("events"."type" = 'Event::User' ) )

Similar that rails search at first for an internal class with such name, and then already external. Certainly I can change a name of an internal class, but it no good for project, maybe have other way?

+1  A: 

I don't quite get what you want to do here. If you want to use STI, then the subclasses of 'Event' model, should be event types, like "Meeting", "Party" or something like that.
class Event::User < Event defines Event::User as an event type. I don't think that is what you want to do.

If what you're trying to do is a one-to-many relation (user can create many events, event has one owner only) then a simpler way to do this would be to add a field in the event model "user_id", and then add the following to the event model:

class Event
  belongs_to :owner, :foreign_key => 'user_id'
end

This allows you to do things like: User.first.events (array of events for the first user), and Event.last.owner (user object representing the owner of the last event)

Faisal