title: How do I validate a virtual attribute in an ActiveRecord model?
body: <p>I am using virtual attributes to save tags in an Entry model from a comma-separated textbox in my form (based on <a href="http://railscasts.com/episodes/167-more-on-virtual-attributes" rel="nofollow noreferrer">Railscasts #167</a>):</p>
  
  <pre><code>class Entry &lt; ActiveRecord::Base
    has_many :entry_tags
    has_many :tags, :through =&gt; :entry_tags
  
    after_save :update_tags
    attr_writer :tag_names
  
    def tag_names
      tags.map(&amp;: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
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>class Tag &lt; ActiveRecord::Base
    has_many :entry_tags
    has_many :entries, :through =&gt; :entry_tags
  
    validates_uniqueness_of :name
    validates_format_of :name, :with =&gt; /\A[a-z0-9_ -]*\Z/, :on =&gt; :create
  end
  </code></pre>
  
  <p>However, because the <code>update_tags</code> method is being called after save, any validation errors from the create would be after the Entry is already saved.</p>
  
  <p>I'm thinking about creating a validation method within the Entry model and calling that on entry save, but:</p>
  
  <ol>
  <li>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 <code>Entry</code> or create a <code>Tag</code> object for each name and check <code>t.valid?</code>? Would I somehow collect validation error messages from <code>Tag</code> or generate them?</li>
  <li>I'm not sure if this is even the right way to do this sort of validation.</li>
  </ol>
  
  <p>Any suggestions?</p>