【问题标题】:field_for and nested form with mongoidfield_for 和带有 mongoid 的嵌套表单
【发布时间】:2011-07-02 00:12:59
【问题描述】:

谁能给我一个使用 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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 mongoid


    【解决方案1】:

    您的模型:

    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
    

    你的控制器:

    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
    

    您的模板:

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

    这应该对你有用!

    朱利安

    【讨论】:

    • 使用 mongoid >= 2.0.0.rc1 你不需要明确说你的模型也应该验证嵌入式模型。这是默认行为。见mongoid.org/docs/upgrading
    • 嗨 Julian Maicher,这仍然是使用 Mongoid 4 的推荐方法吗?
    • 我强烈建议您使用nested_form gem 进行嵌套。此外,如果您使用强参数,这个答案是不完整的。 @Julian 它与 mongoid gem 并没有真正的关系。或者实际上,我所知道的 embeddedhas_many 关联之间的唯一区别是,您不需要 accepts_nested_attributes_for 嵌入的东西
    • @JulianMaicher - 很好的例子。这对我帮助很大。请记住,在 Rails 4 中,最好使用许可而不是直接使用参数。要允许嵌套参数,请执行以下操作:params.require(:employee).permit(:name, :addresses_attributes =&gt; [:address_type, :address, :id],) @CyrilDD - 根据我的测试,embeds_manyaccepts_nested_attributes_for 都是必需的。
    • 预构建建议是黄金!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多