1

I have the following set of classes and relations defined and I want to be able to build a collection of all events which contain at least one story a specific user has been tagged in.

I.e. in my event controller I want to be able to call something like Event.events_user_is_in(@user) which returns every event which contains a story the user has been tagged in.

class Event < ActiveRecord::Base
  has_many :stories
end

class Story < ActiveRecord::Base
  belongs_to :event
  has_many: tags
end

class Tag< ActiveRecord::Base
  belongs_to :story
  belongs_to :user
end

class User< ActiveRecord::Base
  has_many :tags
end

I have been reading about scoping and have successfully generated a scoping on Story which returns only the stories a user was tagged in but I can't see how to do this for events. Any help would be greatly appreciated!

1 Answer 1

2

You can use method or scope if you like:

class Event < ActiveRecord::Base

  scope :events_user_is_in, lambda {|user|
    joins(:stories => :tags).where("tags.user_id = ?", user.id).uniq
  }

end
2
  • Great! That does the join I need, the only problem is that if the user is tagged in multiple stories in the event the event is returned multiple times, is there some kind of distinct keyword I can use to prevent that?
    – owencm
    Jul 22, 2012 at 22:32
  • Sure, you can use 'uniq' method in Rails 3.2, or manually add .select("DISTINCT (events.*)")...
    – bender
    Jul 23, 2012 at 14:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.