On Feb 13, 7:17 pm, Lille <[email protected]> wrote:
> Hi,
>
> I want to specify relationships between two classes like that
> expressed in the following pseudocode:
>
> class User < ActiveRecord::Base
> has_many :projects
> end
>
> class Project < ActiveRecord::Base
>
> has_one :primary_record_owner, :<pseudo_option_for_referring_to>=>"User"
> has_many :record_owners, :<pseudo_option_for_referring_to>=>"User"
> has_many :users # this refers to User, too
> end
>
> From the above I seek the following kind of results:
>
> @user.projects # returns all projects associated with the user from
> any of the three User associations in Project
> @project.primary_record_owner # returns the User instance
> @project.record_owners # returns the collection of User instances
> @project.users # returns User instances, not necessarily overlapping
> with the other associations
>
> The intent I mean to express is that a Project can have any of three
> levels of relationship with a User, while a User has only one level of
> association with a Project.
>
> I was thinking HABTM, but I don't see how to get my desired
> '[email protected]' result from that.
>
This seems like a good place to use a decorated join model with
has_many :through. Code:
class User < AR::Base
has_many :project_links
has_many :projects, :through => :project_links
end
class ProjectLink < AR::Base
belongs_to :user
belongs_to :project
# other fields here:
# primary: boolean, default false
# owner: boolean, default false
end
class Project < AR::Base
has_many :project_links
has_many :users, :through => :project_links, :conditions =>
{ :project_links => { :owner => false } }
has_many :record_owners, :through => :project_links, :source
=> :user, :conditions => { :project_links => { :owner =>
true, :primary => false } }
has_one :primary_owner, :through => :project_links, :source
=> :user, :conditions => { :project_links => { :owner =>
true, :primary => true } }
end
You'll probably need some callbacks to handle the "only one primary
owner" restriction, but everything else should work as written.
--Matt Jones
--
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en.