【问题标题】:Rails: Methods in scopesRails:作用域中的方法
【发布时间】:2011-11-06 06:47:27
【问题描述】:

我的一个模型上有以下方法:

  def remaining_stock
    if initial_stock
      initial_stock - bought_items
    else
      0
    end
  end

在控制器中,我想提取用户拥有的所有剩余库存大于零的项目。所以,简而言之,就像

@remaining_items = Item.where(:user_id => current_user.id).{somehow specify that remaining stock > 0}

该方法类似于

def has_remaining_stock
  remaining_stock > 0
end

但我不知道如何将其添加到查询本身或某种引入 has_remaining_stock 的范围(我可以使用 :conditions 进行范围,但不能使用其他方法)

任何想法表示赞赏。

【问题讨论】:

    标签: ruby-on-rails activerecord scope


    【解决方案1】:

    简短的回答是你无法得到你想要的。请记住,您正在生成要发送到数据库以获取项目的 SQL。 SQL 不包括按行运行的 Ruby,但您可以用它做其他事情。比如:

    .where("initial_stock = NULL or (initial_stock - bought_items) > 0")
    

    应该可以。您可以将其打包为模型的范围,以获得更清晰的语义。您只需要在 SQL 条件中表达函数即可。

    【讨论】:

    • 您确定initial_stock = NULL 有效吗?不应该是initial_stock IS NULL吗?另外,为什么要检查它是否为 null 呢?
    【解决方案2】:

    我想你可以这样做如下:

    scope :has_remaining_stock, where("(initial_stock - bought_items) > 0)")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-14
      • 1970-01-01
      • 2019-04-27
      • 2013-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-23
      相关资源
      最近更新 更多