开发者

Using where in custom model validation

开发者 https://www.devze.com 2023-02-18 14:49 出处:网络
Platform: Rail 3.0 Database: mysql 5.1 Business requirement: Only one item of a product can be issued at a time. After a return of the issued item, a new item can be issued of same product. Multiple

Platform: Rail 3.0

Database: mysql 5.1

Business requirement: Only one item of a product can be issued at a time. After a return of the issued item, a new item can be issued of same product. Multiple items from different products can be issued at a time.

To implement the above business requirement, I am checking if there is already an item issued for the same product within the same date range (by checking to see if there is an overlap of the dates in my where below).

However, I am getting the following exception: NoMethodError: undefined method `where' for Lecture:Module.

I need to be able to use my custom validation to enforce this business requirement. Any ideas? The below is what I have so far:

class Item < ActiveRecord::Base
  validate :valida开发者_StackOverflow社区te_one_item_for_product
  def validate_one_item_for_product
    items = Item.where( "issue_date < ? and return_date > ? and product_id = ?",
                        return_date,
                        issue_date,
                        product_id)
    errors.add( :base,
                "item already issued for this product, not returned yet") if items.size > 0
  end
end


Normally Item.where would work, but for some reason in this case it seems to be having namespacing issues.

self.class.where should be fine.

0

精彩评论

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