现在的位置: 首页 > 综合 > 正文

10个最未充分利用的ActiveRecord::Relation法

2018年09月08日 ⁄ 综合 ⁄ 共 1731字 ⁄ 字号 评论关闭

在这里,我已经收集了十大最未被充分利用的关系方法从该列表中您的阅读喜悦。

10. first_or_create 

使用 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

有时候如果你想查找一个类的记录,你可以使用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 中才有)

同样,有时你想要一个ActiveRecord::Relation,不包含任何对象。返回一个空数组通常不是一个好主意,如果你的API的消费者预期的关系对象。相反,你可以使用没有。
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

将所有的数据一次性加载到内存中处理。但是当我们的Model中table数据过多时,会引起程序崩溃。所以,find_each 方法应运而生

find_each方法,是一次性加载1000条(默认)记录到内存中处理,知道将所有数据都处理完

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

5. to_sql and explain

关系查询

Library.joins(:book).to_sql

Libray.joins(:book).explain

4. find_by (rails
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.select(:title).map(&:title)

published_book_titles = Book.published.map(&:title)

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


http://blog.mitchcrowe.com/blog/2012/04/14/10-most-underused-activerecord-relation-methods/

抱歉!评论已关闭.