本文介绍了field_for和嵌套形式与mongoid的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人可以给我一个使用mongoid的嵌套形式的工作示例吗?
Could somebody give me the working example of nested form using 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
您的控制器:
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 %>
这应该对您有用!
朱利安
这篇关于field_for和嵌套形式与mongoid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!