在自定义模型验证中使用 where
平台:Rail 3.0
数据库:mysql 5.1
业务需求:一种产品一次只能发出一项。退回已发出的商品后,可以发出同一产品的新商品。一次可以发出来自不同产品的多个项目。
为了实现上述业务需求,我正在检查在同一日期范围内是否已经有针对同一产品发布的商品(通过检查下面的 where
中的日期是否存在重叠)。
但是,我收到以下异常:NoMethodError:讲座:模块的未定义方法“where”。
我需要能够使用自定义验证来强制执行此业务要求。有什么想法吗?以下是我到目前为止所拥有的:
class Item < ActiveRecord::Base
validate :validate_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
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 :validate_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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通常
Item.where
可以工作,但由于某种原因,在这种情况下它似乎存在命名空间问题。self.class.where 应该没问题。
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.