[]Rails で十分に活用されていなくてもったいない ActiveRecord::Relation のメソッド TOP 10

これはすごい、全然使える。。。。。。。。。。
http://d.hatena.ne.jp/suginoy/20120605/p3


Myメモ


10位 ブロック付きの first_or_create

Book.where(:title => 'Tale of Two Cities').first_or_create
Book.where(:title => 'Tale of Two Cities').first_or_create do |book|
  book.author = 'Charles Dickens'
  book.published_year = 1859
end

9位 first_or_initialize

Book.where(:title => 'Tale of Two Cities').first_or_initialize

8位 scoped

def search(query)
  if query.blank?
    scoped
  else
    q = "%#{query}%"
    where("title like ? or author like ?", q, q)
  end
end

7位 none ( Rails 4 のみ)

def filter(filter_name)
  case filter_name
  when :all
    scoped
  when :published
    where(:published => true)
  when :unpublished
    where(:published => false)
  else
    none
  end
end


6位 find_each

Book.where(:published => true).find_each do |book|
  puts "Do something with #{book.title} here!"
end


5位 to_sql と explain

  Library.joins(:book).to_sql
  # => SQL query for you database.
  Libray.joins(:book).explain
  # => Database explain for the query.

4位 find_byRails 4 のみ)

Book.where(:title => 'Three Day Road', :author => 'Joseph Boyden').first

代わりに

Book.find_by(:title => 'Three Day Road', :author => 'Joseph Boyden')


3位 scoping

Comment.where(:post_id => 1).scoping do
  Comment.first # SELECT * FROM comments WHERE post_id = 1
end


2位 pluck

published_book_titles = Book.published.pluck(:title)


1位 merge

class Account < ActiveRecord::Base
  # ...

  # Returns all the accounts that have unread messages.
  def self.with_unread_messages
    joins(:messages).merge( Message.unread )
  end
end