【发布时间】:2010-12-30 07:41:16
【问题描述】:
我有一个 Rails 3.0 项目,使用 mongo 和 MongoMapper。我有一个模型,其基本信息描述了一个拥有许多宠物的宠物商店。宠物是一个单独的模型。
我有一个可以让我创建新宠物商店的表单,但是如何在创建新商店的同时添加一个字段来创建宠物?现在我有一个破解的解决方案可以完成我想要的,但我可能有一种 Rails 方式可以做到这一点,对吧?我怎样才能正确地做到这一点,以便我可以在表单字段等上使用验证?
我目前的解决方案是手动修改宠物的表单字段(在表单模板中添加了一个带有 name="petstore[pet]" 的标签。这个表单由 petstore_controller 的 create 方法处理,我添加了代码来创建一个表单域中的宠物
型号:
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
类似的话题/问题:
(我不确定如何将该解决方案映射到我的问题上。)
(接受的答案引用了一个让我有点头疼的 google 组线程......)
【问题讨论】:
标签: ruby-on-rails mongodb mongomapper