就个人而言,为了更传统一点,我会使用
class User < ActiveRecord::Base
scope :has_name, where("users.name != ''")
end
这样,当您的模型与另一个模型连接时,如果多个表有一个name
列,您就不会引入列歧义
考虑这个例子
$ rails new app
$ cd app
$ rails g resource User name:string company_id:integer
$ rails g resource Company name:string
$ rake db:migrate
我们的模型
class User < ActiveRecord::Base
belongs_to :company
scope :has_name, where("name != ''")
end
class Company < ActiveRecord::Base
has_many :users
end
一个问题
$ rails c
irb> User.has_name.join(:company)
哦不!
User Load (0.4ms) SELECT "users".* FROM "users" INNER JOIN
"companies" ON "companies"."id" = "users"."company_id" WHERE
(name != '')
SQLite3::SQLException: ambiguous column name: name: SELECT
"users".* FROM "users" INNER JOIN "companies" ON
"companies"."id" = "users"."company_id" WHERE (name != '')
ActiveRecord::StatementInvalid: SQLite3::SQLException: ambiguous
column name: name: SELECT "users".* FROM "users" INNER JOIN
"companies" ON "companies"."id" = "users"."company_id" WHERE
(name != '')
让我们修复范围
class User < ActiveRecord::Base
belongs_to :company
scope :has_name, where("users.name != ''")
end
重新运行我们的查询
irb> reload!
irb> User.has_name.join(:company)
适当的输出
User Load (0.1ms) SELECT "users".* FROM "users" INNER JOIN "companies"
ON "companies"."id" = "users"."company_id" WHERE (users.name != '')
=> []