【问题标题】:Creating names scoped based on join创建基于连接范围的名称
【发布时间】:2015-02-25 21:08:14
【问题描述】:

我需要根据是否支持 iphone 在我的 rails 项目中过滤“应用程序”。我正在尝试为此目的创建一个命名范围,但出现以下错误。

app/models/app.rb:21: syntax error, unexpected '}', expecting =>
app/models/app.rb:21: syntax error, unexpected '}', expecting =>
app/controllers/apps_controller.rb:5:in `index'

app.rb

named_scope :with_iphone_support,
              joins: :version,
              conditions: {:versions.any{ |v| v.iphone_support == true}}

【问题讨论】:

  • 这是 Rails 2.x 还是更现代的版本?
  • @tadman 它是 4.x,所以我猜需要一个未命名的范围
  • 不确定您是否在处理遗留应用程序。新的scope 方法更加灵活,值得一试。

标签: ruby-on-rails ruby activerecord named-scope


【解决方案1】:

Rails 2 通常应该是这样的:

named_scope :with_iphone_support,
  joins: :version,
  conditions: { versions: { iphone_support: true } }

不可能将块传递给类似的东西。

Rails 3.x 和更高版本使用 scope + where 方法定义范围。

【讨论】:

    【解决方案2】:

    conditions 需要一个哈希,而不是一个块。

    试试这个:

    named_scope :with_iphone_support,
                 conditions: 'exists(select * from versions where iphone_support = 1 and app_id = apps.id)'
    

    【讨论】:

    • 我的错,我忘了删除多余的{}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-03
    • 1970-01-01
    • 2013-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多