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


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


10. first_or_create 

使用 first_or_create

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

通常情况下,你想找到一个记录的某些属性,或创建一个与这些附加属性。要做到这一点简洁,您可以提供一个块
  1. Book.where(:title => 'Tale of Two Cities').first_or_create do |book|  
  2.   book.author = 'Charles Dickens'  
  3.   book.published_year = 1859  
  4. end  

9. first_or_initialize

如果不想创建记录属性可以使用 
  1. Book.where(:title => 'Tale of Two Cities').first_or_initialize  

8. scoped

有时候如果你想查找一个类的记录,你可以使用scoped
  1. def search(query)  
  2.   if query.blank?  
  3.     scoped  
  4.   else  
  5.     q = "%#{query}%"  
  6.     where("title like ? or author like ?", q, q)  
  7.   end  
  8. end  

7. none (rails 4 中才有)

同样,有时你想要一个ActiveRecord::Relation,不包含任何对象。返回一个空数组通常不是一个好主意,如果你的API的消费者预期的关系对象。相反,你可以使用没有。
  1. def filter(filter_name)  
  2.   case filter_name  
  3.   when :all  
  4.     scoped  
  5.   when :published  
  6.     where(:published => true)  
  7.   when :unpublished  
  8.     where(:published => false)  
  9.   else  
  10.     none  
  11.   end  
  12. end  

6. find_each

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

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

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

5. to_sql and explain

关系查询
  1. Library.joins(:book).to_sql  

  1. Libray.joins(:book).explain  

4. find_by (rails 4 中才有)

如可以把
  1. Book.where(:title => 'Three Day Road':author => 'Joseph Boyden').first  

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

3. scoping

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

2. pluck

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

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

  1. published_book_titles = Book.published.pluck(:title)  

1. merge

  1. class Account < ActiveRecord::Base  
  2.   # ...  
  3.   
  4.   # Returns all the accounts that have unread messages.  
  5.   def self.with_unread_messages  
  6.     joins(:messages).merge( Message.unread )  
  7.   end  
  8. end  




http://blog.mitchcrowe.com/blog/2012/04/14/10-most-underused-activerecord-relation-methods/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值