Ruby on Rails
Tuesday, November 25, 2014
Hello,
This is a classic User -> Membership -> Group example with some twist: User is a member of a single Group at any given time. But I want to keep the history which Group the User was a member of.
I am looking for a proper way of doing it.
This is how I think models should look like:
#user.rb
Class User < ActiveRecord::Base
has_many :memberships
has_many :groups, through: :memberships
#membership.rb
Class Membership < ActiveRecord::Base
belongs_to :user
belongs_to :group
#group.rb
Class Group < ActiveRecord::Base
has_many :memberships
has_many :users, through: :memberships
Obviously we need date_from attribute in memberships to keep a track on when the user joined the group.
Creating/Updating is working out of the box. It's querying data I have trouble with.
Now it is easy to get the last group the user is a member of:
#user.rb
...
def latest_group
memberships.order(:date_from).last.group
end
Similarly you can get latest user for a group.
But how to get all users currently belonging to group? Furthermore how to get all the users belonging to group at given date?
Looking forward for your input.
Cheers
Tomas
-- This is a classic User -> Membership -> Group example with some twist: User is a member of a single Group at any given time. But I want to keep the history which Group the User was a member of.
I am looking for a proper way of doing it.
This is how I think models should look like:
#user.rb
Class User < ActiveRecord::Base
has_many :memberships
has_many :groups, through: :memberships
#membership.rb
Class Membership < ActiveRecord::Base
belongs_to :user
belongs_to :group
#group.rb
Class Group < ActiveRecord::Base
has_many :memberships
has_many :users, through: :memberships
Obviously we need date_from attribute in memberships to keep a track on when the user joined the group.
Creating/Updating is working out of the box. It's querying data I have trouble with.
Now it is easy to get the last group the user is a member of:
#user.rb
...
def latest_group
memberships.order(:date_from).last.group
end
Similarly you can get latest user for a group.
But how to get all users currently belonging to group? Furthermore how to get all the users belonging to group at given date?
Looking forward for your input.
Cheers
Tomas
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/95f96649-41ae-4d12-bedb-8cfc782b0841%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment