ruby-on-rails - field_for 和带有 mongoid 的嵌套表单

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

有人可以给我使用 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

最佳答案

您的模型:

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

您的 Controller :
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 %>

那应该对你有用!

朱利安

关于ruby-on-rails - field_for 和带有 mongoid 的嵌套表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5078661/

相关文章:

ruby-on-rails - 什么是 ActionDispatch?

ruby-on-rails - 如何找到 rake 任务的源文件?

ruby-on-rails - Ruby on Rails : Trying to understand Undefined method, nil:NilClass

mongodb - 在 Mongoid 3 中,我可以构建一个 Queryable 然后将它传递给 where 方法吗?

ruby-on-rails - 缓存多级外部 id 是一个好习惯吗

ruby-on-rails - Rails 6 - 如何在 js.erb 文件中包含 javascript_pack_tag

mysql - Ruby on Rails MYSQL 错误访问被拒绝用户 'root@localhost'

ruby-on-rails - Rails - 通用全局函数

ruby-on-rails-3 - 在mongoid中获取至少一个关系对象的模型

ruby-on-rails - 具有父引用的 Mongoid 为空