Hi,
I have 2 articles and I want to get the readers of both articles. How do
I do that ?
Here is the pattern (from AWDWR):
class Article < ActiveRecord::Base
has_many :readings
has_many :readers, :through => :readings, :source => :user
end
class User < ActiveRecord::Base
has_many :readings
has_many :articles, :through => :readings
end
Let’s say we have 2 articles : a1 and a2.
It is easy to get the readers of a1 or a2 :
r1 = a1.readers
r2 = a2.readers
Now, I want to get the readers of a1 AND a2 in one query. How can I do
that simply ?
I know I could do a simple r1 & r2. But I am interested in the rails
query (to add then some other conditions).
I would like to do something like :
User.find(:all, :conditions => “not(articles.find(a1.id).notempty?) &
not(articles.find(a1.id).notempty?)”) (This does not work)
I do not know much about SQL. So If you directly see the SQL request to
do that, it is interesting me too.
Thx
H
User.find(:all, :include=>:articles, :conditions=>[“articles.id in
(?)”, [a1.id, a2.id].join(‘,’)])
On Feb 26, 4:37 pm, Harry S. [email protected]
AndyV wrote:
User.find(:all, :include=>:articles, :conditions=>[“articles.id in
(?)”, [a1.id, a2.id].join(‘,’)])
On Feb 26, 4:37 pm, Harry S. [email protected]
It works well. Thx a lot !
Congrats!
On Feb 28, 5:35 pm, Harry S. [email protected]
I tested this too quickly. Now that I come back to this it appears that
it is actually not working.
The command User.find(:all, :include=>:articles,
:conditions=>[“articles.id in
(?)”, [a1.id, a2.id].join(‘,’)]) returns the users who read one of the
two articles but not only the users who read both.
Any idea of how to get simply the users who read both articles ?
Thx
H
AndyV wrote:
Congrats!
On Feb 28, 5:35 pm, Harry S. [email protected]
Harry S. wrote:
Any idea of how to get simply the users who read both articles ?
Have a look at this thread:
http://www.ruby-forum.com/topic/143618
Various solutions to effectively the same problem.
Thx, actually I have already seen this thread but clearly there is
nothing “simple” in it.
This comes back to the question what is the SQL squery to get the users
who read both articles.
For the moment I will simply do the intersection r1 & r2. It seems that
Rails cannot do much for this question. So I will use SQL when I have
some time.
Thx
H
Mark B. wrote:
Harry S. wrote:
Any idea of how to get simply the users who read both articles ?
Have a look at this thread:
Can anyone solve this sql query - Rails - Ruby-Forum
Various solutions to effectively the same problem.