Given the following two models:
class Company < ActiveRecord::Base
has_many :departments
accepts_nested_attributes_for :departments
end
class Department < ActiveRecord::Base
belongs_to :company
end
I can now create a company and its departments in one go:
@company = Company.create! params[:company]
In this example params[:company]
is expected to look like this:
params[:company] = {
:name => 'Foo Inc',
:departments_attributes => {
1 => { :name => 'Management' },
2 => { :name => 'HR' }
}
}
Notice the :departments_attributes
key!
But if I convert to XML using @company.to_xml
, I get the following:
<company>
<id type="integer">1</id>
<name>Foo Inc</activity>
<departments type="array">
<department>
<id type="integer">1</id>
<company-id type="integer">1</company-id>
<name>Management</name>
</department>
<department>
<id type="integer">2</id>
<company-id type="integer">1</company-id>
<name>HR</name>
</department>
</departments>
</company>
Notice that I here get the nested resources in a container node called <departments>
- not <departments_attributes>
!
Why this inconsistency and is there a way to make Rails accept a POST request using departments instead of departments_attributes as the wrapper?
Am I the only one who thinks this is important when creating API's? It's weird for non-rails folks, that the output can't also be used as input.
How have you solved this - if at all?