Rails + MongoMapper + EmbeddedDocument form help

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-28 19:50:22

Here's the basic approach I took in one of my apps. Problem has many answers - problem is a document, answer is an embedded document. You can use the "add answer" link to generate another answer field, and the "remove" link to delete one.

_form.html.erb:

<% form_for @problem do |f| %>
  <%= f.error_messages %>

  <p>
    <%= f.label :content %><br />
    <%= f.text_area :content, :size => '50x7' %>
  </p>

  ...etc...

  <%= add_answer_link "(add answer)" %>
  <div id="answers">
    <%= render :partial => 'answer', :collection => @problem.answers %>
  </div>

  <p><%= f.submit "Submit" %></p>
<% end %>

_answer.html.erb:

<div class="answer">
  <% fields_for 'problem[answers]', answer, :index => nil do |f| -%>
    <%= f.label :content, "Answer #{answer.id}:" %>
    <%= f.text_field :content, :size => 50 %>
    <%= link_to_function "(remove)", "$(this).up('.answer').remove()" %>
  <% end -%>
</div>

problems_helper.rb

module ProblemsHelper
  def add_answer_link(name)
    link_to_function name do |page|
      page.insert_html :bottom, "answers", :partial => 'answer', :object => Answer.new
    end
  end
end

I cut out a couple minor bits of the implementation, but that should work.

Even easier now -- update for Rails 4.1.1, ruby 2.1.1p76:

Models:

class Location
 include MongoMapper::EmbeddedDocument
  key :state, String, :default => "CA"
  key :zip, String
  timestamps!
end

class House
 include MongoMapper::Document
 timestamps!
 one :location
end

Controller:

def new
    @house = House.new
end

new.html.erb:

<%= form_for @house, url: houses_path do |house_form| %>
<p>
    <%= house_form.label :name %><br>
    <%= house_form.text_field :name %>
</p>

<%= house_form.fields_for :location do |address_fields| %>

    Street  : <%= address_fields.text_field :street %>
    Zip code: <%= address_fields.text_field :zip %>
<% end %>

<p>
    <%= house_form.submit %>
</p>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!