I'm trying to create an object with embedded attributes for testing. This example uses a user with multiple languages but I would love a solution for the general case of creating embedded objects.
Present creation code:
def valid_attributes
{ :languages => [Language.new(language: "en-US", proficiency: "1")] }
end
user = User.create! valid_attributes
The models:
class User
include Mongoid::Document
field :languages
embeds_many :languages
validates_presence_of :languages
attr_accessible :languages_attributes
accepts_nested_attributes_for :languages, :reject_if => lambda { |a| a[:language].blank? }, :allow_destroy => true
end
class Language
include Mongoid::Document
field :language
field :proficiency
key :language
embedded_in :user
attr_accessible :language, :proficiency
end
These models work fine for creating objects from nested forms in Ryan Bates' footsteps (https://github.com/ryanb/complex-form-examples). I don't know whether that is the right way, but I assume so.
There are a few obvious solutions I can see. One is to just hardcode the input like what is generated from the forms:
{"user"=>{ "languages_attributes"=>{"0"=>{"language"=>"en-US", "proficiency"=>"1", "_destroy"=>"false", "id"=>"en-dash-us"}}}
That doesn't seem DRY or sane in the long run, to me.
The other solution is to just cut the embedded objects and use Arrays. Mongoid is pretty good at supporting arrays but you lose the ability to write validations for each object and the code would be less reusable.
Thoughts, Stackoverflowers?