title: Rails 3: alias_method_chain to set specific attribute first
body: <p>When user's create a post I'd like to set the user_id attribute first. I'm trying to do this using alias_method_chain on the arrtibutes method. But I'm not sure if this is right as the problem I thought this would fix is still occurring. Is this correct? </p>
  
  <p>Edit: </p>
  
  <p>When my users create a post they assign 'artist(s)' to belong to each post, using a virtual attribute called 'artist_tokens'. I store the relationships in an artist model and a joined table of artist_ids and post_ids called artisanships. </p>
  
  <p><strong>I'd like to to also store the user_id of whomever created the artist that belongs to their post (and I want it inside the artist model itself), so I have a user_id column on the artist model.</strong></p>
  
  <p>The problem is when I create the artist for each post and try to insert the user_id of the post creator, the user_id keeps showing as NULL. Which is highly likely because the post's user_id attribute hasn't been set yet. </p>
  
  <p>I figured to get around this I needed to set the user_id attribute of the post first, then let the rest of the attributes be set as they normally are. This is where I found alias_method_chain.</p>
  
  <h2>post.rb</h2>
  
  <pre><code> attr_reader :artist_tokens
  
    def artist_tokens=(ids)
      ids.gsub!(/CREATE_(.+?)_END/) do
        Artist.create!(:name =&gt; $1, :user_id =&gt; self.user_id).id
      end
      self.artist_ids = ids.split(",")
    end
  
  
      def attributes_with_user_id_first=(attributes = {})
        if attributes.include?(:user_id)
          self.user_id = attributes.delete(:user_id)
        end
        self.attributes_without_user_id_first = attributes
      end
      alias_method_chain :attributes=, :user_id_first
  </code></pre>
  
  <p>EDIT: </p>
  
  <pre><code>class ArtistsController &lt; ApplicationController
  
    def index
      @artists = Artist.where("name like ?", "%#{params[:q]}%")
      results = @artists.map(&amp;:attributes)
      results &lt;&lt; {:name =&gt; "Add: #{params[:q]}", :id =&gt; "CREATE_#{params[:q]}_END"}
  
      respond_to do |format|
        format.html
        format.json { render :json =&gt; results }
      end
    end
  </code></pre>