field_for和嵌套形式与mongoid

Kir*_*Kir 15 ruby-on-rails mongoid ruby-on-rails-3

有人可以给我使用mongoid的嵌套表单的工作示例吗?

我的模特:

class Employee 
  include Mongoid::Document 
  field :first_name 
  field :last_name 
  embeds_one :address 
end

class Address 
  include Mongoid::Document 
  field :street 
  field :city 
  field :state 
  field :post_code 
  embedded_in :employee, :inverse_of => :address 
end
Run Code Online (Sandbox Code Playgroud)

Jul*_*her 24

你的型号:

class Employee 
  include Mongoid::Document 

  field :first_name 
  field :last_name 
  embeds_one :address
  # validate embedded document with parent document
  validates_associated :address
  # allows you to give f.e. Employee.new a nested hash with attributes for
  # the embedded address object
  # Employee.new({ :first_name => "First Name", :address => { :street => "Street" } })
  accepts_nested_attributes_for :address
end

class Address 
  include Mongoid::Document 

  field :street 
  field :city 
  field :state 
  field :post_code 
  embedded_in :employee, :inverse_of => :address 
end
Run Code Online (Sandbox Code Playgroud)

你的控制器:

class EmployeesController < ApplicationController

  def new
    @employee = Employee.new
    # pre-build address for nested form builder
    @employee.build_address
  end

  def create
    # this will also build the embedded address object 
    # with the nested address parameters
    @employee = Employee.new params[:employee]

    if @employee.save
      # [..]
    end
  end      

end
Run Code Online (Sandbox Code Playgroud)

你的模板:

# new.html.erb
<%= form_for @employee do |f| %>
  <!-- [..] -->
  <%= f.fields_for :address  do |builder| %>
     <table>
       <tr>
         <td><%= builder.label :street %></td>
         <td><%= builder.text_field :street %></td>
       </tr>
       <!-- [..] -->
     </table>
  <% end %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

这对你有用!

朱利安

  • 使用mongoid> = 2.0.0.rc1,您无需明确说明您的模型也应验证嵌入式模型.这是默认行为.见http://mongoid.org/docs/upgrading (2认同)
  • @JulianMaicher - 很好的例子.这对我帮助很大.请记住,在Rails 4中,最好使用许可证直接使用params.允许嵌套的params执行此操作:`params.require(:employee).permit(:name,:addresses_attributes => [:address_type,:address,:id],)`@ CoderDD - 从我的测试'embeds_many`和` accepts_nested_attributes_for`是必需的. (2认同)