0
p = Person.find_by_id(1, :include => :bags, :conditions => ['bag.id in (?), [3,4])

I would like to know how I could make sure this query will only be valid if both 'items.id' '3' & '4' are present rather than '3' or/and '4'.

Thanks

5
  • Please explain a bit more what you're trying to accomplish. Commented Oct 15, 2010 at 5:54
  • In Plain SGL : SELECT * FROM persons p INNER JOIN bags_persons b1 ON b1.person_id = p.id INNER JOIN bags_persons b2 ON b2.person_id = p.id WHERE b1.bag_id = 3 AND b2.bag_id = 4 The point is you need to join 2 times in order to search for both bags at the same time. Maybe there is a neater way to write it in rails, but with :joins and :conditions you'll be able to translate this query into the find syntax. Commented Oct 15, 2010 at 7:00
  • Btw, :include is mainly used to prefetch the bags in the resulting person Object, so if you don't access the bags of it after this request :joins will be enough. Commented Oct 15, 2010 at 7:04
  • What's the setup? person has_many :bags and bag belongs_to person? Commented Oct 15, 2010 at 10:29
  • @jacob I am trying to run a single query that will return the person only if they have the associated bags. @marko The setup is "person has_many :persons_bags, has_many :bags, :through => :peoples_bags", "peoples_bag belongs_to :person, belongs_to :bag", and "bags has_many :peoples_bag" Commented Oct 16, 2010 at 20:58

1 Answer 1

1

You need to manually construct your 2 inner joins to the bags_persons table:

Person.find_by_id(1, :joins => "INNER JOIN bags_persons bp1 ON bp1.person_id=persons.id INNER JOIN bags_persons bp2 ON bp2.person_id=persons.id", :conditions => "bp1.bag_id=3 AND bp2.bag_id=4")

Hope this helps

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.