首页 > 在Rails里,关于 scope 以及 where 的两个疑问

在Rails里,关于 scope 以及 where 的两个疑问

环境:Rails4.0 + Ruby2.0

问题1:

有这么一段代码

class Article < ActiveRecord::Base
    scope :recent, -> { find_by( name: 'rails' }
end

Article.recent

当数据库中存在 name: 'rails' 的记录时,一切正常。
但是当数据中不存在 name: 'rails' 的记录时,返回了 all 数据。

请问是什么原因?

问题2:

在 model 里, 有个类型为「boolean」的属性。执行语句:

Article.where( home: true )     => 返回正常 (返回 home 为 true 的记录)

SQL语句为:  select xxx from xxx where 'article.home' = 'f'

Article.where( home: false)     => 返回不正常(数据库是有 home 为 false 的记录的)但是返回为空。

SQL语句为:  select xxx from xxx where 'article.home' = 't'

Article.where( home: 'false') => 返回正常。
  1. 请问为什么第二步会返回不正常?
  2. 为什么 sql 语句的查询方式有点奇怪,不是应该为 where 'article.home' = true 么?

一切真相大白了: 我在migration文件中写错了, 把 false 写成了 :false , 写成了字符串( 这样居然不会报错,好吧,sqlite的原因,mysql 的话直接报错)

sqlite下: boolean 类型的值,true 为 't' , false 为 'f' 。
mysql下: boolean 类型的值,true 为 true, false 为 false

sql语句查询:

sqlite: select xx from xx where 'xx' = ' t / f'
mysql: select xx from xx where 'xx' = ' 0 / 1 / true / false ' ( 在rails下统一为 0 / 1 )

【热门文章】
【热门文章】