在Rails 3中使用范围

时间:2011-08-16 02:36:55

标签: ruby-on-rails ruby-on-rails-3 sqlite

我正在尝试在我的帐户模型中定义范围,但它无效。这是我的代码:

class Account < ActiveRecord::Base

    has_many :organizations

    scope :primary, joins(:organizations).where('organizations.primary = ?', true)

    accepts_nested_attributes_for :organizations
end

class Organization < ActiveRecord::Base

    belongs_to :account

    has_many :locations

    accepts_nested_attributes_for :locations
end

在控制台中,我尝试了以下命令:

Account.primary.first

但是我收到以下错误:

ActiveRecord::StatementInvalid: SQLLite3::SQLException: near "primary":
syntax error: SELECT "accounts".* FROM "accounts" INNER JOIN "organizations" ON
"organizations"."account_id" = "accounts"."id" WHERE (organizations.primary = 't')
LIMIT 1

我认为“主要”这个名称可能会导致问题。当我将范围重命名为“重要”并尝试我得到:

NoMethodError: undefined method 'important' for #<Class:0x1f4a900>

如果有人可以提供帮助,我会非常感激。

1 个答案:

答案 0 :(得分:2)

我认为您的问题是您有一个名为“primary”的,而且是reserved word。试着引用它:

scope :primary, joins(:organizations).where('organizations."primary" = ?', true)

此例外:

  

SQLLite3 :: SQLException:靠近“primary”:

来自SQLite,而不是来自ActiveRecord或Rails。