Combine two ActiveRecord::Relation objects

Suppose I have the following two objects: first_name_relation = User.where(:first_name => ‘Tobias’) # ActiveRecord::Relation last_name_relation = User.where(:last_name => ‘Fünke’) # ActiveRecord::Relation is it possible to combine the two relations to produce one ActiveRecord::Relation object containing both conditions? Note: I’m aware that I can chain the wheres to get this behavior, what I’m really interested in … Read more

Want to find records with no associated records in Rails

Consider a simple association… class Person has_many :friends end class Friend belongs_to :person end What is the cleanest way to get all persons that have NO friends in ARel and/or meta_where? And then what about a has_many :through version class Person has_many :contacts has_many :friends, :through => :contacts, :uniq => true end class Friend has_many … Read more

Rails where condition using NOT NIL

Using the rails 3 style how would I write the opposite of: Foo.includes(:bar).where(:bars=>{:id=>nil}) I want to find where id is NOT nil. I tried: Foo.includes(:bar).where(:bars=>{:id=>!nil}).to_sql But that returns: => “SELECT \”foos\”.* FROM \”foos\” WHERE (\”bars\”.\”id\” = 1)” That’s definitely not what I need, and almost seems like a bug in ARel. 5 Answers 5