诗歌rails 之 exists?的用法

很多时候,会用到这样的检查,配合collection的empty?和返回结果的blank?

exists?有些时候很方便
Returns true if a record exists in the table that matches the id or conditions given, or false otherwise. The argument can take five forms:

    * Integer - Finds the record with this primary key.
    * String - Finds the record with a primary key corresponding to this string (such as ‘5‘).
    * Array - Finds the record that matches these find-style conditions (such as [‘color = ?’, ‘red’]).
    * Hash - Finds the record that matches these find-style conditions (such as {:color => ‘red’}).
    * No args - Returns false if the table is empty, true otherwise.

For more information about specifying conditions as a Hash or Array, see the Conditions section in the introduction to ActiveRecord::Base.

Note: You can‘t pass in a condition as a string (like name = ‘Jamie‘), since it would be sanitized and then queried against the primary key column, like id = ‘name = \’Jamie\’‘.
Examples

Ruby代码
  1. Person.exists?(5)  
  2. Person.exists?('5')  
  3. Person.exists?(:name => "David")  
  4. Person.exists?(['name LIKE ?'"%#{query}%"])  
  5. Person.exists?  

posted @ 2009-08-18 11:32  麦飞  阅读(595)  评论(0编辑  收藏  举报