简体   繁体   English

如何在ActiveRecord模型中验证虚拟属性?

[英]How do I validate a virtual attribute in an ActiveRecord model?

I am using virtual attributes to save tags in an Entry model from a comma-separated textbox in my form (based on Railscasts #167 ): 我正在使用虚拟属性从我的表单中的逗号分隔文本框中保存条目模型中的标签(基于Railscasts#167 ):

class Entry < ActiveRecord::Base
  has_many :entry_tags
  has_many :tags, :through => :entry_tags

  after_save :update_tags
  attr_writer :tag_names

  def tag_names
    tags.map(&:name).join(", ")
  end

  def update_tags
    if @tag_names
      self.tags = @tag_names.split(",").map do |name|
        Tag.find_or_create_by_name(name.strip)
      end
    end
  end
  private :update_tags
end

I want to add validation on my Tag names, but I'm not sure what the best way to do that would be. 我想在我的标签名称上添加验证,但我不确定最好的方法是什么。 I have an existing validation method defined in the Tag model: 我有一个在Tag模型中定义的现有验证方法:

class Tag < ActiveRecord::Base
  has_many :entry_tags
  has_many :entries, :through => :entry_tags

  validates_uniqueness_of :name
  validates_format_of :name, :with => /\A[a-z0-9_ -]*\Z/, :on => :create
end

However, because the update_tags method is being called after save, any validation errors from the create would be after the Entry is already saved. 但是,由于在保存后调用了update_tags方法,因此创建的任何验证错误都将在Entry已保存之后。

I'm thinking about creating a validation method within the Entry model and calling that on entry save, but: 我正在考虑在Entry模型中创建一个验证方法并在条目保存时调用它,但是:

  1. If I do that, I'm not sure what the best way to do the validation would be. 如果我这样做,我不确定验证的最佳方法是什么。 Do I create my own validation within Entry or create a Tag object for each name and check t.valid? 我是否在Entry创建自己的验证或为每个名称创建一个Tag对象并检查t.valid? ? Would I somehow collect validation error messages from Tag or generate them? 我会以某种方式从Tag收集验证错误消息或生成它们吗?
  2. I'm not sure if this is even the right way to do this sort of validation. 我不确定这是否是进行此类验证的正确方法。

Any suggestions? 有什么建议?

如果你还没有排除它,我会看一下使用validates_associated

This error comes up when you try to add an invalid item to an association. 当您尝试将无效项添加到关联时,会出现此错误。 A possible cause is that you added a validation to the associated model after entering data, and you currently have invalid values in the database. 可能的原因是您在输入数据后向关联模型添加了验证,并且您当前在数据库中具有无效值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM