1

I got two models: Source and SourceType. Source of course belongs to SourceType.
I want to create new source and assign proper sourcetype object to it. 'Proper' means that one virtual attribute of the source object match some of sourceType objects test regexpression, which becomes source's Type.

I got an attribute writer in source object

class Source < ActiveRecord::Base
   belongs_to :source_type    
   def url=(value)
       SourceType.each do |type|
          # here i match type's regexp to input value and if match, 
          # assign it to the new source object
       end
   end
end

I don't want to build any custom validator for it'll be need to run through SourceTypes twice. How to raise validate error if no sourcetypes is fit to the input so user could see error reasons in a form?

4

1 回答 1

2

验证

如果您使用 设置虚拟属性attr_accessor,您应该能够在您发送数据的模型上进行验证(inverse_of如果您想在嵌套模型上进行验证,也可以使用):

http://api.rubyonrails.org/classes/ActiveModel/Validator.html

这现在可以与 validates 方法结合使用(参见 ActiveModel::Validations::ClassMethods.validates 了解更多信息)。

class Person
  include ActiveModel::Validations
  attr_accessor :title

  validates :title, presence: true
end

代码

我会这样做:

class Source < ActiveRecord::Base
   belongs_to :source_type, inverse_of: :sources
   attr_accessor :url
end

class SourceType < ActiveRecord::Base
   has_many :sources, inverse_of: :source_type
   validates :source_type_attr, presence: { if: :url_match? }

   def url_match?
      self.sources.url == [your_regex]
   end
end
于 2014-04-07T08:37:26.107 回答