DEV Community

n350071πŸ‡―πŸ‡΅
n350071πŸ‡―πŸ‡΅

Posted on • Edited on

rails query

First of all, Scope is same as Class method

def self.with_suger
  where("suger > 0")    
end
Enter fullscreen mode Exit fullscreen mode

This is same as

scope :with_suger, -> {
  where("suger > 0")    
}
Enter fullscreen mode Exit fullscreen mode

and then, use it as class method.

BendingMachine.with_suger
Enter fullscreen mode Exit fullscreen mode

cut in

#{table_name} is useful 😎

  • I'd recommend you to use this, otherwise, you will see this error message when you join and merge the scope with another model scope.
  • Especially, when your model name and table name is different, you easily go into confusing. But this way, you'll be still in Object World.
ActiveRecord::StatementInvalid:
  Mysql2::Error: Column 'created_at' in where clause is ambiguous:
Enter fullscreen mode Exit fullscreen mode
scope :created_until_the_day, -> (date) {
  where("#{table_name}.created_at < ?",  date)
}
Enter fullscreen mode Exit fullscreen mode

πŸ‘ Simple Scope

scope :creator_filter, -> {
  where(creator: true)
}
Enter fullscreen mode Exit fullscreen mode
scope :over_x_years_old, (x)-> {
  where('age >= ?', x)
}
Enter fullscreen mode Exit fullscreen mode

πŸ¦„join table

It makes "Inner Join" on with the relation.

scope :with_authored_book, -> {
  joins(:book)
}
Enter fullscreen mode Exit fullscreen mode

πŸ¦„πŸ¦„join Multi Scope

scope :with_authored_book_and_laptop, -> {
  joins(:book, :laptop)
}
Enter fullscreen mode Exit fullscreen mode

πŸ”πŸ₯Hierarchy Scope

scope :with_authored_book_of_abc_publisher, -> {
  joins(book: :publisher)
}
Enter fullscreen mode Exit fullscreen mode

πŸ”πŸ₯πŸ¦„πŸ¦„ Hierarchy and multi Scope

scope :with_authored_book_of_abc_publisher, -> {
  joins(:laptop, {book: :publisher})
}
Enter fullscreen mode Exit fullscreen mode

πŸ”πŸ₯ WHERE with Hierarchy scope

You can write both ways.

.where(User.table_name => {name: 'john connor'})
.where("#{User.table_name}.name = ?", 'john connor')
Enter fullscreen mode Exit fullscreen mode

Merge

without merge

joins(:user)
.where("#{User.table_name}.name = ?", 'john connor')
Enter fullscreen mode Exit fullscreen mode

or

joins(:user)
.where(User.table_name => {name: 'john connor'})
Enter fullscreen mode Exit fullscreen mode

With Merge

joins(:user)
.merge(User.where(name: 'john connor'))
Enter fullscreen mode Exit fullscreen mode

EXISTS

WHERE NOT exists (
  SELECT *
  FROM users
  WHERE users.company_id = :company_id
    AND users.story_id = stories.id
)
Enter fullscreen mode Exit fullscreen mode
.where(User.joins(:company, :story).where(comapny_id: company_id).exists.not)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)