Issue when retrieving records with empty array

In Rails 4 you can use User.where.not(id: []) which will give you the correct result. It produces: SELECT “users”.* FROM “users” WHERE (1 = 1) Unfortunately User.where(‘id NOT IN (?)’, []) should be equivalent but it is not. It still gives you the wrong result: SELECT “users”.* FROM “users” WHERE (id NOT IN (NULL)) References: … Read more

How do you scope ActiveRecord associations in Rails 3?

I suggest you take a look at “Named scopes are dead” The author explains there how powerful Arel is 🙂 I hope it’ll help. EDIT #1 March 2014 As some comments state, the difference is now a matter of personal taste. However, I still personally recommend to avoid exposing Arel’s scope to an upper layer … Read more

ActiveRecord Arel OR condition

ActiveRecord queries are ActiveRecord::Relation objects (which maddeningly do not support or), not Arel objects (which do). [ UPDATE: as of Rails 5, “or” is supported in ActiveRecord::Relation; see https://stackoverflow.com/a/33248299/190135 ] But luckily, their where method accepts ARel query objects. So if User < ActiveRecord::Base… users = User.arel_table query = User.where(users[:kind].eq(‘admin’).or(users[:kind].eq(‘author’))) query.to_sql now shows the reassuring: … Read more

How to use unscoped on associated relations in Rails3?

Oh. I fooled myself. Thought the following would not work… but it does: Product.unscoped do my_photo.product end Notice that you have to call unscoped on the model with the default_scope that should be bypassed. Also, inheritance has to be respected. If you have class InsuranceProduct < Productand class FinancialProduct < Product and a default_scope in … Read more

Subqueries in activerecord

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 “messages” WHERE “messages”.”user_id” IN (SELECT user_id FROM “profiles” WHERE “profiles”.”gender” = ‘m’) (the version number that “now” refers to is most likely 3.2)

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)