ActiveRecord Count Question

In the language of my domain, a Community has many Media and a Media has
many Viewings. I’m drawing a blank trying to find a clean way to get the
count of unviewed Media by Community for a User.

def community
has_many :medias
end

def media
has_many :viewings
belongs_to :media
end

def viewing
belongs_to :media
belongs_to :user
end

def user
has_many :viewings
end

The trouble I’m having is finding a way to represent “not in” or “not
exists” sql constructs in an ActiveRecord query. If I were to manually
write out the query for a single community it might look like:

select count(*) from media where community_id = @community_id and not
exists (select * from viewings where user_id = @user_id and media_id =
media.media_id)

Any ideas on how to convert this into a beautiful, one-line statement in
ActiveRecord would be much appreciated.

If the number of media is small, you might just take the difference of
the “total media” and the “media viewed …”

(What are these media?)

Stephan

Jeff wrote:

In the language of my domain, a Community has many Media and a Media has
many Viewings. I’m drawing a blank trying to find a clean way to get the
count of unviewed Media by Community for a User.

def community
has_many :medias
end

def media
has_many :viewings
belongs_to :media
end

def viewing
belongs_to :media
belongs_to :user
end

def user
has_many :viewings
end

The trouble I’m having is finding a way to represent “not in” or “not
exists” sql constructs in an ActiveRecord query. If I were to manually
write out the query for a single community it might look like:

select count(*) from media where community_id = @community_id and not
exists (select * from viewings where user_id = @user_id and media_id =
media.media_id)

Any ideas on how to convert this into a beautiful, one-line statement in
ActiveRecord would be much appreciated.