scoping Blogs
Written by Kiprosh, team of passionate and disciplined craftsmen turning your ideas into reality.
Kiprosh is now part of LawLytics
Written by Kiprosh, team of passionate and disciplined craftsmen turning your ideas into reality.
In Rails, multiple scopes can be created and chained together. What if we wish to apply a specific scope to a group of queries? Consider the following scenario: we have Post and Comment models and we want to perform few operations on public posts. # app/models/post.rb class Post < ActiveRecord::Base scope :public, -> { where(private: false) } endLoading development environment (Rails 7.0.0.alpha2) 3.0.0 :001 > Post.public.update_all(body: 'public post') Post Update All (4.1ms) UPDATE "posts" SET "body" = ? WHERE "posts"."private" = ? [["body", "public post"], ["private", 0]] 3.0.0
We were debugging one issue in our application which was caching the scope we had in where clause for first_or_create in model callbacks - and found one interesting issue - Theconditions in the where clause were cached in after_create callback if we use where().first_or_create, please check example below - Example: Contact.where(first_name: 'Kiprosh').first_or_create Contact Model: after_create :sanitize def sanitize Contact.where(creator_id: 123).solr_index end This should fire Contact.where(creator_id: 123) but instead fires Contact.where(first_name: 'Kiprosh', creator_id: 123) On further