class Ecard include MongoMapper::Document key :family, String key :given, String key :additional, String key :prefix, String key :suffix, String has_many :emails end class Email include MongoMapper::EmbeddedDocument key :pref, Boolean key :email, String end
def new @ecard = Ecard.new respond_to do |format| format.html # new.html.erb format.json { render json: @ecard } end end
以我的形式
<%= form_for(@ecard) do |f| %>
<%= f.label t :family, :scope => :name %><br />
<%= f.text_field :family %><br />
<%= @ecard.emails.each do |email| %>
<%= f.fields_for email, :index => email do |e| %>
<%= e.label :pref %>
<%= e.check_box :pref %>
<%= e.label :email %>
<%= e.text_field :email %>
<% end %>
<% end %>
<% end %>
如何创建新的电子邮件嵌套资源?
答案 0 :(得分:1)
虽然mongomapper不支持“accepts_nested_attributes_for”,但以下内容适用于我 使用rails 3.2.7,mongo_mapper 0.11.2,mongo 1.6.4,bson 1.6.4。 经常参考“rake routes”直到路由正确,即url_for,控制器方法等。 请注意email.id的隐藏字段以及包含创建新电子邮件项的路径的按钮。 这仅适用于嵌入式关联中的新项目(您可以完成放置/更新)。 希望这有助于你前进。
-Gary
应用程序/控制器/ ecards_controller.rb
class EcardsController < ApplicationController
def new
@ecard = Ecard.create
respond_to do |format|
format.html { render :template => 'ecards/show' }
format.json { render json: @ecard }
end
end
def show
@ecard = Ecard.find(params[:id])
respond_to do |format|
format.html { render :template => 'ecards/show' }
format.json { render json: @ecard }
end
end
end
应用程序/控制器/ emails_controller.rb
class EmailsController < ApplicationController
def new
@ecard = Ecard.find(params[:ecard_id])
@ecard.emails << Email.new
@ecard.save
respond_to do |format|
format.html { render :template => 'ecards/show' }
format.json { render json: @ecard }
end
end
end
应用程序/视图/电子贺卡/ show.html.erb
<%= form_for(@ecard) do |f| %>
<%= f.label :family, :scope => :name %><br />
<%= f.text_field :family %><br />
<% @ecard.emails.each do |email| %>
<%= f.fields_for email, :index => email do |e| %>
<%= e.hidden_field :id, :value => email.id %>
<%= e.label :pref %>
<%= e.check_box :pref %>
<%= e.label :email %>
<%= e.text_field :email %>
<br/>
<% end %>
<% end %>
<% end %>
<%= button_to 'New Email', url_for([:new, @ecard, :email]), :method => :get %>
配置/ routes.rb中
resources :ecards do
resources :emails
end