开发者

Using scopes in Rails 3

I am trying to define a scope in my Account model but it is not working. Here is my code:

class Account < ActiveRecord::Base

    has_many :organiz开发者_JAVA百科ations

    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

From the console, I tried the following command:

Account.primary.first

But I get the following error:

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

I think the name 'primary' might be causing the problem. When I renamed the scope to "important" and tried that I get:

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

If anyone can help I would very much appreciate it.


I think your problem is that you have a column named "primary" and that's a reserved word. Try quoting it:

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

This exception:

SQLLite3::SQLException: near "primary":

is coming from SQLite, not from ActiveRecord or Rails.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜