Showing posts with label rails-activerecord. Show all posts
Showing posts with label rails-activerecord. Show all posts

Monday, April 16, 2018

Eager loading an association of a singular association from an instantiated ActiveRecord object in Rails 5

Leave a Comment

I have a model User, that has_one :child, and the Child model has_one :toy.

If I have a single instance of the User class user, how can I load both the child and toy in one query?

Here's what doesn't work:

user.child.toy # 2 queries user.includes(child: :toy) # can't call includes on a single record user.child.includes(:toy) # same as above user.association(:child).scope.eager_load(:toy).first # makes the appropriate query with both child and toy... but doesn't set the object on the user model. user.child = user.association(:child).scope.eager_load(:toy).first # makes the appropriate query, but also calls another query before setting the child :( 

Is there any way to do this that doesn't involve re-querying the user model. ie. I want to avoid this

User.where(id: user.id).eager_load(child: :toy).first 

Relavant model declarations:

class User < ActiveRecord::Base   has_one :child   has_one :toy, through: :child end  class Child < ActiveRecord::Base   has_one :toy   belongs_to :user end  class Toy < ActiveRecord::Base   belongs_to :child end 

Update

This works, but isn't ideal. I don't think I should have to declare another relation solely for this reason.

class User < ActiveRecord::Base   has_one :child   has_one :toy, through: :child   has_one :child_with_toy, ->{ eager_loads(:toy) }, class_name: "Child", foreign_key: :parent_id end 

which allows me to call user.child_with_toy to get the Child object, and user.child_with_toy.toy to get the Toy object, while only triggering one SQL query.

1 Answers

Answers 1

The eager loading API is designed for collections to prevent N+1 queries.

Loading an association of a singular association of a single record is not an N+1 case.

Personally, I don't think saving 1 query is worth the extra cognitive overhead to the programmer in this particular case. Eager loading is more worthwhile if you are working with an array of instantiated records (e.g. users) or a collection association (e.g. children).

If you really want to eager load an association of a singular association for an already-instantiated record, you can do this:

user.association(:child).target = user.association(:child).scope.eager_load(:toy).first 

This is similar to the last approach you listed at the top of your question.

However, I think your :child_with_toy approach is cleaner.

To be clear: This is well off the beaten path of typical ActiveRecord usage, and I'm having difficulty imagining a scenario where I would recommend doing this.

It's up to you --- just weigh the costs.

Read More

Wednesday, February 7, 2018

Rails: eager-loading on an already-left-joined table?

Leave a Comment

We are already left-joining a table so that we can order by a column, if the relation exists:

people = Person   .joins("LEFT JOIN addresses ON addresses.id = people.address_id")   .order("addresses.country")   .all 

This results in a single SQL query, but I'd like to have people.first.address not trigger SQL to load the address. I am left-joining because some people don't have addresses.

.includes(:address) triggers a separate query.

You can do what I'm suggesting with inner joins, using includes, but that triggers 2 SQL queries:

Person.includes(:address).all 

While joins + includes triggers only one (but INNER joins):

Person.joins(:address).includes(:address).all 

Active record also uses left joins if you force a join while eager-loading .eager_load(:addresses).

Can you take an existing left-join and have rails eager-load with those results? So far I can't find this.

3 Answers

Answers 1

Well, in your case you could select your query creating an alias for the fields you are going to use from address something like this:

people = Person          .joins("LEFT JOIN addresses ON addresses.id = people.address_id")          .select("people.*, addresses.country as address_country")          .order("address_country")          .all 

This won't change your desired query and will not result in extra queries, not for country at least.

Answers 2

Try this:

people = Person.   eager_load(:address).   merge(Address.order("coalesce(country, '')")).   all  people.first.address 

eager_load forces eager loading by performing a LEFT OUTER JOIN.

I added a coalesce on country so you have more control over where people without addresses appear in the results.

Here is what it looks like for me:

people = Person.   eager_load(:address).   merge(Address.order("coalesce(country, '')")).   all  (0.5ms)  SELECT DISTINCT COUNT(DISTINCT "people"."id") FROM "people" LEFT OUTER JOIN "addresses" ON "addresses"."person_id" = "people"."id" SQL (2.1ms)  SELECT "people"."id" AS t0_r0, "people"."name" AS t0_r1, "people"."created_at" AS t0_r2, "people"."updated_at" AS t0_r3, "addresses"."id" AS t1_r0, "addresses"."person_id" AS t1_r1, "addresses"."address" AS t1_r2, "addresses"."country" AS t1_r3, "addresses"."created_at" AS t1_r4, "addresses"."updated_at" AS t1_r5 FROM "people" LEFT OUTER JOIN "addresses" ON "addresses"."person_id" = "people"."id" ORDER BY coalesce(addresses.country, '')   people.first.address nil  people.last.address #<Address:0x007febabb508a8> {             :id => 1,      :person_id => 4,        :address => "24175 Gerhold Prairie",        :country => "O",     :created_at => Thu, 01 Feb 2018 18:47:45 UTC +00:00,     :updated_at => Thu, 01 Feb 2018 18:47:45 UTC +00:00 } 

Note that no queries are run when you access the addresses

I'll point that you've ordered by a table that left outer joined, so you need to decide how you want to treat nulls.

Answers 3

You can uses #references with #includes to LEFT JOIN your relation and achieve what you are after.

people = Person   .includes(:addresses)   .references(:addresses)   .order("addresses.country") 

This will yield one query and all the people, whether or not they have an address, and also eager load the addresses to avoid the dreaded N + 1 queries.

The documentation doesn't do a great job of explaining that #references will add a LEFT JOIN but it's purpose is to allow adding SQL clauses (WHERE, ORDER, GROUP, etc.) on the relation in conjunction with #includes.

Read More

Friday, February 2, 2018

What can I write to fix ActiveRecord::RecordNotUnique?

Leave a Comment

I can't seem to shake this exception. I have the following code:

class Batch < ApplicationRecord    before_create :upcase_session_id         def self.for_session(session_id, opts)     batch = Batch.where(session_id: session_id.upcase).first_or_initialize     if batch.new_record?       batch.property = opts[:property]       batch.save!     end     batch   end    private    def upcase_session_id     self.session_id = session_id.upcase   end end 

Calling Code:

def retrieve_batch     self.batch ||= Batch.for_session(batch_session_id, property: property) end 

I'm not sure how I can change this code to stop getting this exception that I keep getting.

1 Answers

Answers 1

The exception is raised when a record cannot be inserted because it would violate a uniqueness constraint. You should tell us the table constraints because the problem could be any column.

You could try this:

class Batch < ApplicationRecord    def self.for_session(session_id, opts)     Batch.where(session_id: session_id.upcase).first_or_create(property: opts[:property])   end  end 
Read More

Wednesday, September 6, 2017

ActiveRecord pluck to SQL

Leave a Comment

I know these two statements perform the same SQL:

Using select

User.select(:email) # SELECT  `users`.`email` FROM `users` 

And using pluck

User.all.pluck(:email) # SELECT `users`.`email` FROM `users` 

Now I need to get the SQL statement derived from each method. Given that the select method returns an ActiveRecord::Relation, I can call the to_sql method. However, I cannot figure out how to get the SQL statement derived from a pluck operation on an ActiveRecord::Relation object, given that the result is an array.

Please, take into account that this is a simplification of the problem. The number of attributes plucked can be arbitrarily high.

Any help would be appreciated.

2 Answers

Answers 1

You cannot chain to_sql with pluck as it doesn't return ActiveRecord::relation. If you try to do, it throws an exception like so

NoMethodError: undefined method `to_sql' for [[""]]:Array 

I cannot figure out how to get the SQL statement derived from a pluck operation on an ActiveRecord::Relation object, given that the result is an array.

Well, as @cschroed pointed out in the comments, they both(select and pluck) perform same SQL queries. The only difference is that pluck return an array instead of ActiveRecord::Relation. It doesn't matter how many attributes you are trying to pluck, the SQL statement will be same as select

Example:

User.select(:first_name,:email) #=> SELECT "users"."first_name", "users"."email" FROM "users" 

Same for pluck too

User.all.pluck(:first_name,:email) #=> SELECT "users"."first_name", "users"."email" FROM "users" 

So, you just need to take the SQL statement returned by the select and believe that it is the same for the pluck. That's it!

Answers 2

You could monkey-patch the ActiveRecord::LogSubscriber class and provide a singleton that would register any active record queries, even the ones that doesn't return ActiveRecord::Relation objects:

class QueriesRegister   include Singleton   def queries     @queries ||= []   end    def flush     @queries = []   end end  module ActiveRecord  class LogSubscriber < ActiveSupport::LogSubscriber    def sql(event)     QueriesRegister.instance.queries << event.payload[:sql]     "#{event.payload[:name]} (#{event.duration}) #{event.payload[:sql]}"       end  end end 

Run you query:

User.all.pluck(:email) 

Then, to retrieve the queries:

QueriesRegister.instance.queries 
Read More

Sunday, June 19, 2016

Add computable column to multi-table select clause with eager_load in Ruby on Rails Activerecord

Leave a Comment

I have a query with a lot of joins and I'm eager_loading some of associations at the time. And I need to compute some value as attribute of one of models.

So, I'm trying this code:

ServiceObject   .joins([{service_days: :ou}, :address])   .eager_load(:address, :service_days)   .where(ous: {id: OU.where(sector_code: 5)})   .select('SDO_CONTAINS(ous.service_area_shape, SDO_GEOMETRY(2001, 8307, sdo_point_type(addresses.lat, addresses.lng, NULL), NULL, NULL) ) AS in_zone') 

Where SQL function call in select operates data from associated addresses and ous tables.

I'm getting next SQL (so my in_zone column getting calculated and returned as first column before other columns for all eager_loaded models):

SELECT SDO_CONTAINS(ous.service_area_shape, SDO_GEOMETRY(2001, 8307, sdo_point_type(addresses.lat, addresses.lng, NULL), NULL, NULL) ) AS in_zone, "SERVICE_OBJECTS"."ID" AS t0_r0, "SERVICE_OBJECTS"."TYPE" AS t0_r1, <omitted for brevity> AS t2_r36 FROM "SERVICE_OBJECTS" INNER JOIN "SERVICE_DAYS" ON "SERVICE_DAYS"."SERVICE_OBJECT_ID" = "SERVICE_OBJECTS"."ID" INNER JOIN "OUS" ON "OUS"."ID" = "SERVICE_DAYS"."OU_ID" INNER JOIN "ADDRESSES" ON "ADDRESSES"."ID" = "SERVICE_OBJECTS"."ADDRESS_ID" WHERE "OUS"."ID" IN (SELECT "OUS"."ID" FROM "OUS" WHERE "OUS"."SECTOR_CODE" = :a1)  [["sector_code", "5"]] 

But it seems like that in_zone isn't accessible from either model used in query.

I need to have calculated in_zone as attribute of ServiceObject model object, how I can accomplish that?

Ruby on Rails 4.2.6, Ruby 2.3.0, oracle_enhanced adapter 1.6.7, Oracle 12.1

2 Answers

Answers 1

I have successfully replicated your issue and it turns out that this is a known issue in Rails. The problem is that when using eager_load, Rails maps the columns of all eager-loaded tables into table and column aliases in the form of t0_r0, t0_r1, etc... (you can see these in the SQL that you pasted in the question). And while doing that, it simply ignores the custom columns in the select, probably because it cannot determine which eager-loaded table it should attribute the custom column to. It is sad that this issue is open for more than 2 years now...

Nevertheless I think I found a workaround. It seems that if you don't eager load the tables but manually join them (with joins), you can as well include them (with includes) and the custom columns will be returned as there will be no column aliasing taking place. The point is that you must not use associations in the joins clauses but you have to specify the joins yourself. Also note that you must specify all columns from the main table in the select manually too (see the service_objects.* in the select).

Try the following approach:

ServiceObject   .joins('INNER JOIN "SERVICE_DAYS" ON "SERVICE_DAYS"."SERVICE_OBJECT_ID" = "SERVICE_OBJECTS"."ID"')   .joins('INNER JOIN "OUS" ON "OUS"."ID" = "SERVICE_DAYS"."OU_ID"')   .joins('INNER JOIN "ADDRESSES" ON "ADDRESSES"."ID" = "SERVICE_OBJECTS"."ADDRESS_ID"')   .includes(:service_days, :address)   .where(ous: {id: OU.where(sector_code: 5)})   .select('service_objects.*, SDO_CONTAINS(ous.service_area_shape, SDO_GEOMETRY(2001, 8307, sdo_point_type(addresses.lat, addresses.lng, NULL), NULL, NULL) ) AS in_zone') 

The computation in the select should still work as the related tables are joined together but there should be no column aliasing present.

Of course this approach means that you'll get three queries instead of just one but unless you return a huge amount of records, the following two queries run by the includes clause should be very fast as they simply load the relevant records using foreign keys.

Answers 2

That monkey patch helped @Envek:

module ActiveRecord   class Base     attr_accessor :_row_   end    module Associations     class JoinDependency       JoinBase && class JoinPart         def instantiate_with_row(row, *args)           instantiate_without_row(row, *args).tap { |i| i._row_ = row }         end; alias_method_chain :instantiate, :row       end     end   end end 

then it is possible to do:

ServiceObject   .joins([{service_days: :ou}, :address])   .eager_load(:address, :service_days)   .where(ous: {id: OU.where(sector_code: 5)})   .select('SDO_CONTAINS(ous.service_area_shape, SDO_GEOMETRY(2001, 8307, sdo_point_type(addresses.lat, addresses.lng, NULL), NULL, NULL) ) AS in_zone')   .first   ._row_['in_zone'] 
Read More

Friday, April 1, 2016

Rails: Validate uniqueness of multiple columns

Leave a Comment

Is there a rails-way way to validate that an actual record is unique and not just a column? For example, a friendship model / table should not be able to have multiple identical records like:

user_id: 10 | friend_id: 20 user_id: 10 | friend_id: 20 

3 Answers

Answers 1

You can scope a validates_uniqueness_of call as follows.

validates_uniqueness_of :user_id, :scope => :friend_id 

Answers 2

You can use validates to validate uniqueness on one attribute:

validates :user_id, uniqueness: {scope: :friend_id} 

The syntax for the validation on multiple columns is similar, but you should provide an array of fields instead:

validates :attr, uniqueness: {scope: [:attr1, ... , :attrn]} 

However, approaches that are shown above suffer from race conditions, consider the following example:

  1. database table records are supposed to be unique by n fields;

  2. multiple (two or more) concurrent requests, handled by separate processes each (application server, sidekiq or whatever you are using), try to write the same record to the table;

  3. each process in parallel validates if there is a record with the same n fields;

  4. validation for each request is passed and each process creates a record in the table with the same data.

To avoid this kind of behaviour, one should add a unique constraint to the db table. You can set it with add_index for multiple (or one) fields by running the following migration:

class AddUniqueConstraints < ActiveRecord::Migration   def change    add_index :table_name, [:field1, ... , :fieldn], unique: true   end end 

Caveat : even after you've set the unique constraint, two or more concurrent requests will try to write the same data to the db, but instead of creating duplicate records, this will result in the raise of the ActiveRecord::RecordNotUnique exception, which you should handle separately:

begin # writing to the database rescue ActiveRecord::RecordNotUnique => e # handling the case when record already exists end  

Answers 3

You probably do need actual constraints on the db, because validates suffers from race conditions.

validates_uniqueness_of :user_id, :scope => :friend_id 

When you persist a user instance, Rails will validate your model by running a SELECT query to see if any user records already exist with the provided user_id. Assuming the record proves to be valid, Rails will run the INSERT statement to persist the user. This works great if you’re running a single instance of a single process/thread web server.

In case two processes/threads are trying to create a user with the same user_id around the same time, the following situation may arise. Race condition with validates

With unique indexes on the db in place, the above situation will play out as follows. Unique indexes on db

Answer taken from this blog post - http://robots.thoughtbot.com/the-perils-of-uniqueness-validations

Read More