On 15 October 2012 21:08, Noxx <mailn...@googlemail.com> wrote:
> 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) }

I wonder if it is confused by the fact that you have explicitly put
"attachments" in the where clause.  Does it make a difference if you
put where("expires_at IS NULL or expires_at >= ?", Time.now)

You have not told us which version of Rails you are using.

Colin

>   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`.`id` AND
>     attachments.expires_at IS NULL or attachments.expires_at >= '2012-10-15
> 21:56:10 +0200'
>   WHERE `attachments`.`user_id` IN (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.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Ruby on Rails: Talk" group.
> To post to this group, send email to rubyonrails-talk@googlegroups.com.
> To unsubscribe from this group, send email to
> rubyonrails-talk+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msg/rubyonrails-talk/-/sxrH9_YQfNMJ.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to