简体   繁体   English

Rails:范围内的方法

[英]Rails: Methods in scopes

I have the following method on one of my models: 我的一种模型具有以下方法:

  def remaining_stock
    if initial_stock
      initial_stock - bought_items
    else
      0
    end
  end

In the controller, I'd like to pull all items owned by the user which have a remaining stock greater than zero. 在控制器中,我要提取用户拥有的剩余库存大于零的所有物品。 So, in short, something like 简而言之,类似

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

The method would be something along the lines of 该方法将类似于

def has_remaining_stock
  remaining_stock > 0
end

But I can't figure out how to add that to either the query itself, or some sort of scope which pulls in has_remaining_stock (I can scope with :conditions, but not other methods) 但是我不知道如何将其添加到查询本身,或者某种类型的范围中,它会引入has_remaining_stock(我可以使用:conditions进行范围调整,但不能使用其他方法进行范围调整)

Any ideas appreciated. 任何想法表示赞赏。

The short answer is that you can't get what you want. 简短的答案是,您无法获得想要的东西。 Remember, you're generating SQL to be sent off to the database to fetch items. 记住,您正在生成要发送到数据库以获取项目的SQL。 SQL doesn't include Ruby to run per row, but you can do other things with it. SQL不包括按行运行的Ruby,但是您可以使用它来做其他事情。 Something like: 就像是:

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

should work. 应该管用。 You could package that up as a scope on your model for cleaner semantics. 您可以将其打包为模型的作用域,以获得更清晰的语义。 You just need to express the function in an SQL condition. 您只需要在SQL条件下表达该函数即可。

我想您可以执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM