ruby-on-rails - 在 Rails 3 中使用作用域

标签 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

我认为名称“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/

相关文章:

ruby-on-rails - 从救援/提升错误中获取实例

ruby-on-rails - Ruby 中有效子域的正则表达式

ruby-on-rails - 使用自定义 Controller 功能提交表单

android - 多列 ListView 显示零而不是数据库值

android - sqlite3权限被拒绝android

ios - 多个表和关系

ruby-on-rails - 使用键的值作为同一散列中另一个键的值的一部分

ruby-on-rails - 仅适用于 JSON 的 Rails 脚手架

ruby-on-rails - Cancan:json的能力类

ruby-on-rails-3 - webrat_steps.rb 丢失