Friday, 23 May 2014

Using Named Scopes Across Models with ActiveRecord #Merge

If you want to use named scopes on joined models, then there are two ways to find the solution.


1. Define a named scope inside each model : you can define a different named scope in each model. lets have an example:

we have two models named user and project. these model have associations lke this,

class User < ActiveRecord::Base

  has_many :projects


end
 --------------------------------------------------------------------------------------------------------------------------------
class Project < ActiveRecord::Base

  belongs_to :user


  scope :available, -> {where(available: true)}
  scope :unavailable, -> {where(available: false)}



end

now if we to get the all projects that are available by the scope then we have to define a named scope inside the user model.

 scope :available_projects, -> {joins(:projects).where("projects.available = ?" ,true)}



2. Use Merge to use defined named scope in another model: 
Other way to use named scope just use merge in your query as like:

 User.joins(:projects).merge(Project.available)
User.joins(:projects).merge(Project.unavailable)








there is no need to have an extra named scope inside the user only one query can can do the same thing as the scope available_projects do.

No comments:

Post a Comment