Ruby on rails 从Rails中的虚拟属性引发验证错误

Ruby on rails 从Rails中的虚拟属性引发验证错误,ruby-on-rails,validation,ruby-on-rails-4,virtual-attribute,Ruby On Rails,Validation,Ruby On Rails 4,Virtual Attribute,我有两个模型:Source和SourceType。源当然属于源类型。 我想创建新的源并为其分配适当的sourcetype对象。”“正确”表示源对象的一个虚拟属性与某些sourceType对象test regexpression匹配,这将成为源的类型。 源对象中有一个属性编写器 class Source < ActiveRecord::Base belongs_to :source_type def url=(value) SourceType.each d

我有两个模型:Source和SourceType。源当然属于源类型。
我想创建新的源并为其分配适当的sourcetype对象。”“正确”表示源对象的一个虚拟属性与某些sourceType对象test regexpression匹配,这将成为源的类型。

源对象中有一个属性编写器

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
类源

我不想构建任何自定义验证器,因为它需要运行两次SourceTypes。如果没有适合输入的源类型,如何引发验证错误,以便用户可以在表单中查看错误原因?

验证

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

现在可以将其与validates方法结合使用(有关详细信息,请参阅ActiveModel::Validations::ClassMethods.validates)


代码

我会这样做:

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
类源
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