I've got a Rails 3.0 project, using mongo with MongoMapper. I've got a model with basic info describing a petstore which has_many pets. A pet is a separate model.
I have a form that lets me create new petstores, but how do I add a field to create a pet at the same time as I create the new store? Right now I have a hacked in solution that accomplishes what I want, but I there's probably a Rails Way to do this, huh? How can I do it properly, so that I can use validations on the form fields and such?
My current solution involves hacking in a form field for the pet manually (added an tag with name="petstore[pet]" in the form template. This form is handled by petstore_controller's create method, and I added code to create a pet from the form field
Models:
class Petstore
include MongoMapper::Document
many :pets, :dependent => :destroy
key :name, String
key :address, String
end
class Pet
include MongoMapper::Document
belongs_to :petstore
key :petstore_id, ObjectID, :required=>true
key :type, String, :required=>true
key :name, String
end
_form.html.erb
<%=form_for @petstore do |f| %>
<li>
<%= f.label :name %>
<%= f.text_field :name, :placeholder =>"The name" %>
</li>
<li>
<%= f.label :address %>
<%= f.text_field :address, :placeholder =>'The address' %>
</li>
<li>
<label for="petstore_pet">Type of pet</label>
<input type="text" id="petstore_pet" name="petstore[pet]">
<li>
<%= f.submit "Submit" %>
</li>
<% end %>
petstores_controller.rb
def create
pet = @petstore.pets.build :type => params[:petstore][:pet]
pet.save if pet
respond_to do |format|
...
end
end
Similar topics/questions:
(I'm not exactly sure how to map that solution onto my question.)
(Accepted answer references a google group thread that is a little over my head...)