Let’s say you have a Rails model with a simple composed_of address.
class User < ActiveRecord::Base
composed_of :address, :mapping => [%w(street street), %w(city city)]
end
class Address
attr_reader :street, :city
def initialize(street, city)
@street, @city = street, city
end
end
And a view that uses fields_for to pass in the field values.
<% form_for :user do |f| -%>
<% f.fields_for :address do |ff| -%>
<%= ff.text_field :street %>
<%= ff.text_field :city %>
<% end -%>
<% end -%>
Looks just like all of those examples online, right? After submitting your new form, though, you will receive the following error.
NoMethodError: undefined method `street' for {:street=>"123 Main Street", :city=>"Denver"}:HashWithIndifferentAccess
This is because out of the box, composed_of does not allow you to use your model this way. You need to create a custom converter, as shown in the following example.
class User < ActiveRecord::Base
composed_of :address, :mapping => [%w(street street), %w(city city)],
:converter => Proc.new {|args| Address.new(args[:street], args[:city])}
end
Now, when we submit our form, the User model knows exactly how to convert the “address” hash into an “Address” object.

