title: Ruby on Rails: compose attribute of model from virtual attributes
body: <p>I have attribute <strong>name</strong> of model Person.</p>
  
  <p>I want to use html-form with fields: <strong>first_name</strong> and <strong>surname</strong>:</p>
  
  <pre><code>&lt;%= f.text_field first_name%&gt;
  &lt;%= f.text_field surname%&gt;
  </code></pre>
  
  <p>And I want to compose these virtual attributes to model attribute <strong>name</strong>.</p>
  
  <p>What's the best way to do it?</p>
  
  <p>I tried to use <a href="http://apidock.com/rails/ActiveRecord/Aggregations/ClassMethods/composed_of" rel="nofollow noreferrer">composed_of</a>, but failed...</p>
  
  <pre><code>class Person &lt; ActiveRecord::Base
    composed_of :name, :class_name =&gt; 'Name', :mapping =&gt; %w(name output_name)
  end
  
  class Name
    attr_reader :output_name
    def initialize(first_name, surname)
      @output_name = first_name + surname
    end
  end
  
  @person.attributes= {"name(1s)" =&gt; 'Alex', "name(2s)" =&gt; 'Bolduin' }
  @person.name.should == 'Alex Bolduin'
  
  expected: "Alex Bolduin",
  got: #&lt;Name:0x000000049d4c08 @output_name="Alex Bolduin"&gt; (using ==)
  </code></pre>
  
  <p>I use Ruby on Rails 3, but I think solution is similar for Rails 3 and Rails 2.3</p>