更新(2010 年 12 月 4 日):
我意识到每个validates
line 实际上是一个方法调用(显然),因此像这样要求它们并不完全符合我的预期。
这有效,但我不确定它是否正确(完全限定 Auction
类名):
class Auction::Validations
Auction.validates :status, :presence => true,
:inclusion => { :in => [
Auction::CREATING,
Auction::OPEN,
Auction::PENDING,
Auction::CANCELLED,
Auction::SUSPENDED,
Auction::EXPIRED,
Auction::CLOSING_COMPLETED,
Auction::CLOSING_WON,
Auction::COMPLETED,
Auction::WON,
Auction::NEGOTIATING,
Auction::IN_ESCROW
] }
Auction.validates :user, :presence => true
Auction.validates :url, :presence => true,
# FIXME: Move this to a URLValidator and do :url => true
:format => /^https?:\/\/[a-z0-9-]+(\.[a-z0-9-])*\.[a-z0-9]+\/.*/i
Auction.validates :title, :presence => true,
:length => { :maximum => 255 }
Auction.validates :description, :presence => true
Auction.validates :reserve, :numericality => { :greater_than_or_equal_to => :minimum_bid }
end
当需要时 (
require 'auction/validations
) 进入 Auction
类,它做正确的事情。原问题如下:
我的几个模型类被所有这些“验证”调用弄得有点困惑,所以我想我可以将它们移到一个单独的类中并“要求”它,但它似乎不起作用。
class Auction < ActiveRecord::Base
require 'auction/validations'
...
class Auction::Validations
include ActiveModel::Validations
validates :status, :presence => true,
:inclusion => { :in => [
... snip ...
] }
validates :user, :presence => true
validates :url, :presence => true,
# FIXME: Move this to a URLValidator
:format => /^https?:\/\/[a-z0-9-]+(\.[a-z0-9-])*\.[a-z0-9]+\/.*/i
validates :title, :presence => true,
:length => { :maximum => 255 }
validates :description, :presence => true
validates :reserve, :numericality => { :greater_than_or_equal_to => :minimum_bid }
validates_each :status, :on => :update do |auction, status_attr, value|
if auction.state_machine.current_state != value
# FIXME: Raise an Exception instead; this is a developer error, not a user error
auction.errors.add status_attr, "Status cannot be changed directly"
end
end
end
它没有错误,但 validates_each 根本不执行该块(通过添加
puts "here"
进行测试),并且数值检查不再起作用。将这个类的主体盲目复制回 Auction 类,一切正常。
我是否误解了“要求”对这些验证的作用?
编辑:
事实上,所有验证都不起作用。不只是那两个。嗯。
最佳答案
我不确定这是否正确,但它以某种方式对我有用:
module MyValidations
module User
def self.included(base)
base.validates_presence_of :firstname
end
end end
然后你可以打电话
User.class_eval do
include MyValidations::User
end
希望有帮助。
关于ruby-on-rails - rails : Keeping all the ActiveRecord "validates" lines in a separate file?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3967097/