我试图在我的帐户模型中定义范围,但它不起作用。这是我的代码:
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
我认为名称“primary”可能会导致问题。当我将范围重命名为“重要”并尝试时,我得到:
NoMethodError: undefined method 'important' for #<Class:0x1f4a900>
如果有人可以提供帮助,我将非常感激。
最佳答案
我认为你的问题是你有一个名为“primary”的列,它是 reserved word 。尝试引用它:
scope :primary, joins(:organizations).where('organizations."primary" = ?', true)
此异常:
SQLLite3::SQLException: near "primary":
来自 SQLite,而不是来自 ActiveRecord 或 Rails。
关于ruby-on-rails - 在 Rails 3 中使用作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7073064/