Thursday, 5 September 2013

using scopes with parameters and has_and_belongs_to_many associations with ActiveRecord (Ruby)

using scopes with parameters and has_and_belongs_to_many associations with
ActiveRecord (Ruby)

In my Sinatra app my model defines a HABTM relationship between Users and
Notifications. I am trying to define a couple of scopes, one for all
Notifications associated with no Users called unread and one that returns
all Notifications that are 'unread' by a particular User.
class Notification < ActiveRecord::Base
has_and_belongs_to_many :users
scope :unread, {
joins: "LEFT JOIN notifications_users ON notifications.id =
notifications_users.notification_id",
conditions: "notifications_users.user_id IS NULL",
select: "DISTINCT notifications.*"
}
scope :unread_by, ->(u){
joins: "LEFT JOIN notifications_users ON notifications.id =
notifications_users.notification_id",
conditions: ["notifications_users.user_id IS ?", u.id],
select: "DISTINCT notifications.*"
}
end
The unread scope works fine but the unread_by scope is throwing a syntax
error. I've tried a few obvious variations on this theme but can't quite
get it to work. How ought I be doing this?

No comments:

Post a Comment