Domanda

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!

È stato utile?

Soluzione

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top