以 Rails 形式处理 MongoMapper EmbeddedDocument
首先,我对一般编程和 Rails 都是新手。我选择 Rails 是因为它看起来是一种很容易上手的语言。对于我的项目,我将 MongoMapper 与 Rails 结合使用。
我正在尝试以与文档相同的形式处理嵌入文档。
我有以下模型:
class User
include MongoMapper::Document
key :email, String, :required => true
key :first_name, String
key :last_name, String
key :role, String
many :addresses
timestamps!
end
class Address
include MongoMapper::EmbeddedDocument
key :location, String
key :street, String
key :city, String
key :zip, Integer
key :state, String
key :country, String
end
我想在创建/编辑文档的同时创建/编辑嵌入文档。我尝试过使用 fields_for:
<% f.fields_for :address, @user.addresses do |address| -%>
<div class="field">
<%= address.label :street %><br />
<%= address.text_field :street %>
</div>
<% end %>
但我得到
#<\Array:0x0000010126e3f8> 的未定义方法“street”
先感谢您。
First of all, I'm new to programming in general and new to Rails. I picked up Rails because it seems an easy language to start with. For my project I'm using MongoMapper with Rails.
I'm trying to process an Embedded Document in the same form as the Document.
I have the following model:
class User
include MongoMapper::Document
key :email, String, :required => true
key :first_name, String
key :last_name, String
key :role, String
many :addresses
timestamps!
end
class Address
include MongoMapper::EmbeddedDocument
key :location, String
key :street, String
key :city, String
key :zip, Integer
key :state, String
key :country, String
end
I want to create/edit the EmbeddedDocument at the same time as the Document. I have tried using fields_for:
<% f.fields_for :address, @user.addresses do |address| -%>
<div class="field">
<%= address.label :street %><br />
<%= address.text_field :street %>
</div>
<% end %>
But I get
undefined method `street' for #<\Array:0x0000010126e3f8>
Thank you in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您在
User
上定义addresses_attributes=
,fields_for
将起作用。由于某种原因,如果您定义该方法,fields_for
实际上会更改其行为。这是一个示例实现:
未经测试,因此您必须解决问题。特别是,如果地址是全新的,因为用户是新的,我不记得嵌套参数如何以不同的方式通过。
fields_for
will work if you defineaddresses_attributes=
onUser
. For some reasonfields_for
actually changes its behavior if you define that method.Here's an example implementation:
Untested, so you'll have to work out the kinks. In particular, I don't remember how the nested parameters come through differently if the addresses are completely new because the user is new.
据我记得 fields_for 不包含对象的 id,为此您需要添加一个隐藏字段。
那么你的addresses_attributes =方法将如下所示:
谢谢Brian,这为我遇到的类似问题提供了解决方案。
As far as I remember fields_for does not include the id of the object, for that you will need to add a hidden field.
Then your addresses_attributes= method would look like this:
Thanks Brian, this provide a solution to a similar problem I was having.