0
クラスEカード
  インクルード MongoMapper::Document

  キー:ファミリー、文字列
  キー: 与えられた、文字列
  キー:追加、文字列
  キー:プレフィックス、文字列
  キー:サフィックス、文字列

  has_many :メール

終わり

クラスメール
  インクルード MongoMapper::EmbeddedDocument

  key :pref、ブール値
  キー:メール、文字列

終わり

eカードコントローラーで

新しい定義
    @ecard = Ecard.new

    Respond_to do |フォーマット|
      format.html # new.html.erb
      format.json { レンダリング json: @ecard }
    終わり
  終わり

そして私の形で

<%= 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 %>

新しい電子メールのネストされたリソースを作成する方法は?

4

1 に答える 1

1

mongomapper は「accepts_nested_attributes_for」をサポートしていませんが、レール 3.2.7、mongo_mapper 0.11.2、mongo 1.6.4、bson 1.6.4 では次のように動作します。url_for、コントローラ メソッドなどのルーティングが正しくなるまで、「rake routes」を頻繁に参照してください。email.id の非表示フィールドと、新しいメール アイテムを作成するためのルートのボタンに注意してください。これは、埋め込まれたアソシエーション内の新しいアイテムのためのものです (put/update を完了する必要があります)。これがあなたの前進に役立つことを願っています。

-ゲイリー

アプリ/コントローラー/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

app/controllers/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

アプリ/ビュー/ecards/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 %>

config/routes.rb

resources :ecards do
    resources :emails
end
于 2012-08-07T14:45:53.650 に答える