【问题标题】:Using scopes in Rails 3在 Rails 3 中使用范围
【发布时间】:2011-10-27 17:37:14
【问题描述】:

我正在尝试在我的 Account 模型中定义一个范围,但它不起作用。这是我的代码:

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>

如果有人能提供帮助,我将不胜感激。

【问题讨论】:

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


    【解决方案1】:

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

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

    这个例外:

    SQLLite3::SQLException: 在“主要”附近:

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

    【讨论】:

    • 不,引号没有运气。还有其他想法吗?感谢您的帮助。
    • @Corey:同样的例外还是新的?
    • 同样的异常。但是我将“primary”列更改为“primary_organization”并且它有效。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2011-11-20
    • 1970-01-01
    • 1970-01-01
    • 2011-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多