铁轨”是否可以知道验证方法中正在执行的操作(更新、创建)?
平台:铁路3.0 数据库:mysql 5.1
业务需求:一种产品一次只能发出一项。退回已发出的商品后,可以发出同一产品的新商品。一次可以发出来自不同产品的多个项目。
为了实现上述业务要求,我正在检查同一日期范围内是否已经有针对同一产品发出的项目(通过检查下面我的位置中的日期是否有重叠)。
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).
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
Validation defined above works fine on create but in case of update i need to implement different logic. I do not want to define two methods for same requirement. so i want to implement checks with function based upon whether its update or create operation.Is there any way i can know if operation which triggered validate is update or delete?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
简单的解决方案是定义一个带有参数的方法来验证它,然后使用不同的
:on =>
调用进行两次验证,然后调用第一个带有参数的方法。另外,如果有帮助,您可以使用
new_record?
它会告诉您是否正在创建对象(在保存之前)Simple solution is to define a method to validate it, with a parameter, and then have two validations with different
:on =>
calls, that in turn call the first method with a parameter.Also, if it helps, you might use
new_record?
which will tell you if the object is being created (before it is saved)验证可以随时运行,而不仅仅是在
create
、save
、update_attributes
等内运行。因此,即使您知道什么方法触发了验证(您可以使用调用者
的输出进行修改),您不应该使用它,因为它可能是完全有效但完全出乎意料的东西。然而,一切并没有失去。您可以通过调用
persisted?
来检查记录是否已被持久化。Validations can be run at any time, not just within
create
,save
,update_attributes
, etc. So even if you could know what method triggered the validation (you can hack around with the output ofcaller
), you should not make any use of it because it could be something completely valid yet completely unexpected.However, all is not lost. You can check whether the record has been persisted yet by calling
persisted?
.