Hi there.
I hope someone can help me and give a tipp how to solve this issue.
I have three models, which you can see below (I pasted only the
necessary
parts):
*class User
has_many :attachments
end
class Folder
has_many :attachments
end
class Attachment
belongs_to :folder
belongs_to :user
scope :valid, lambda { where(“attachments.expires_at IS NULL or
attachments.expires_at >= ?”, Time.now) }
default_scope valid
end*
Now I want to select only folders which have at least one attachment
belonging to the selected user(s).
I’m using:
*users = -List-of-Users-
Folder.joins(:attachments).where(:attachments => {:user_id =>
users}).group(“folders.id”).having(“COUNT(DISTINCT(attachments.user_id))=#{users.size}”)
*
The resulting sql-query is:
SELECT folders. FROM folders
INNER JOIN attachments ON*
-
attachments.folder_id=folders.idAND
attachments.expires_at IS NULL or attachments.expires_at >=
‘2012-10-15 21:56:10 +0200’* - WHERE
attachments.user_idIN (1)
GROUP BY folders.id
HAVING COUNT(DISTINCT(attachments.user_id))=1
*The bold text hilights my issue.
As you can see, there is an OR-statement which renders the join on
attachment.folder_id=folders.id useless.
That’s not really what I expected.
Now my question is: Is this the normal behavior how rails should react?
Is there a way to work around?
I already tried to get brackets around the OR-statement by using
scope :valid, lambda { where("(attachments.expires_at IS NULL or
attachments.expires_at >= ?)", Time.now) }
but this didn’t fix this issue. Rails seems to delete them.
Any help would be very appreciated.
Greetings.
