arel

Subqueries in activerecord

喜夏-厌秋 提交于 2019-11-26 07:26:39
问题 With SQL I can easily do sub-queries like this User.where(:id => Account.where(..).select(:user_id)) This produces: SELECT * FROM users WHERE id IN (SELECT user_id FROM accounts WHERE ..) How can I do this using rails\' 3 activerecord/ arel/ meta_where? I do need/ want real subqueries, no ruby workarounds (using several queries). 回答1: Rails now does this by default :) Message.where(user_id: Profile.select("user_id").where(gender: 'm')) will produce the following SQL SELECT "messages".* FROM

Rails where condition using NOT NIL

て烟熏妆下的殇ゞ 提交于 2019-11-26 06:54:07
问题 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. 回答1: The canonical way to do this with Rails 3: Foo.includes(:bar).where("bars.id IS NOT NULL") ActiveRecord 4.0 and above

ActiveRecord Arel OR condition

旧街凉风 提交于 2019-11-26 06:06:30
问题 How can you combine 2 different conditions using logical OR instead of AND? NOTE: 2 conditions are generated as rails scopes and can\'t be easily changed into something like where(\"x or y\") directly. Simple example: admins = User.where(:kind => :admin) authors = User.where(:kind => :author) It\'s easy to apply AND condition (which for this particular case is meaningless): (admins.merge authors).to_sql #=> select ... from ... where kind = \'admin\' AND kind = \'author\' But how can you

Want to find records with no associated records in Rails

情到浓时终转凉″ 提交于 2019-11-26 05:45:26
问题 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 :contacts has_many :people, :through => :contacts, :uniq => true end class Contact belongs_to :friend belongs_to :person end I really don\

Combine two ActiveRecord::Relation objects

天涯浪子 提交于 2019-11-26 04:36:47
问题 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 is the case where I have two separate ActiveRecord::Relation objects. 回答1