简体   繁体   中英

How do I call a static function with model scopes in Rails?

I wasn't sure how to get it to work syntax wise. I did get it to work like the following though:

  scope :out_of_stock, lambda{ |company| get_inventory(company, 'out_of_stock') }
  scope :in_stock, lambda{ |company| get_inventory(company, 'in_stock') }


  def self.get_inventory(company, stock_status)
    StockInventory.find_all_by_....
  end

However, is there a way to do it without the anonymous functions?

First of all, there are no static functions in Ruby. The self.get_inventory is a class method, which is in effect a singleton instance method on the Company class. The scope call is itself a class method that dynamically defines other class methods, in this case out_of_stock and in_stock .

Second, it's hard to tell what you're trying to do, since you didn't include your entire method, but I'll assume you're trying to get the instances of StockInventory that have a particular company id and inventory status.

ActiveRecord allows you to use finders , as it appears you've done here, or relations , which are a bit more flexible, as they are typically chainable, and because their execution is delayed until absolutely necessary, meaning you can pass them around to different methods without hitting the database. Unless I'm looking up a single object with a known id, I usually stick to relations for this reason.

I'm going to make a few assumptions, since your question isn't particularly clear. If you have defined a relation between Company and StockInventory (like has_many :stock_inventories and belongs_to :company ), you can use that relation as a starting point and defined a method like this on the StockInventory class:

def self.in_stock
  where(stock_status: "in stock") # or whatever
end

Note that instead of passing in a Company instance as an argument to a Company class method that ultimately loads some other class (this should be a red flag), you call this directly on the StockInventory class or any StockInventory relation. Plus, since it's a relation, you can chain other ActiveRecord methods to it, ie my_company.stock_inventories.in_stock.limit(10) .

You'll need to alter this method to fit your particular database columns and statuses, but this is as complicated as it needs to get.

Whatever the case, I recommend you read the Active Record Query Interface guide - there's a lot you can do with it once you understand how it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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