title: How to persist virtual attributes across validation errors and form redirects?
body: <p>I'm setting up an autocomplete association following this <a href="http://railscasts.com/episodes/102-auto-complete-association-revised?view=asciicast" rel="nofollow">Railscast</a>.</p>
  
  <p>I'm using <code>find_or_initialize</code> rather than <code>find_or_create</code> on the virtual category_name attribute, as I need to pass the value through some other logic.</p>
  
  <p>What is the best way to persist this virtual attribute if the parent model validations fail (Product in the railscast). I want the <code>category_name</code> entered by the user to remain after the save path renders the form if there is an error.</p>
  
  <p>I thought the value would be accessible through <code>params[:category_name]</code>, but I am unable to set it back to the field. </p>
  
  <p>Grateful for any ideas.</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>Controller</p>
  
  <pre><code>class ProductsController &lt; ApplicationController
  
    ...
  
    def create
      @product = current_user.products.build(params[:prerep])
  
      if @products.save
        DO SOME STUFF...
  
        respond_to do |format|
          format.html { redirect_to(@product, :notice =&gt; 'Product was successfully created.') }
          format.xml  { render :xml =&gt; @product, :status =&gt; :created, :location =&gt; @product }
        end
  
      else
        respond_to do |format|
          format.html { render :action =&gt; "new" }
          format.xml  { render :xml =&gt; @product.errors, :status =&gt; :unprocessable_entity }
        end
      end
    end
  end
  </code></pre>
  
  <p>Model:</p>
  
  <pre><code>class Prerep &lt; ActiveRecord::Base
    attr_accessible ..., :category_name, ... 
    attr_reader ...
    attr_accessor ...
  
    belongs_to :user, :category
  
    has_many ...
  
    validates ...
  
    def category_name
      category.try(:name)
    end  
  
    def category_name=(name)
      product_category = Category.find_or_initialize_by_name(name) if name.present?
      self.category = if product_category.new_record?
        product_category ...SET SOME ATTRIBUTES...
        product_category.save(:validate =&gt; false)
        product_category
      else
        product_category
      end
    end
  end
  </code></pre>