以Rails的形式处理MongoMapper EmbeddedDocument [英] Handling MongoMapper EmbeddedDocument in Rails form
问题描述
我试图用与Document相同的格式处理嵌入式文档。 b
我有以下模型:
class User
include MongoMapper :: Document
key:email,String,:required => true
key:first_name,String
key:last_name,String
key:role,String
many:addresses
timestamps!
结束
类地址
包含MongoMapper :: EmbeddedDocument
key:location,String
key:street,String
key:city,String
key:zip,Integer
key:state,String
key:country,String
end
我想在Document的同时创建/编辑EmbeddedDocument。我尝试过使用fields_for:
<%f.fields_for:address,@ user.addresses do | address | - %GT;
< div class =field>
<%= address.label:street%>< br />
<%= address.text_field:street%>
< / div>
<%end%>
但我得到
未定义的方法`street'for#< \Array:0x0000010126e3f8>
预先感谢您。
fields_for
如果您定义 addresses_attributes =
在用户
上。出于某种原因, fields_for
会在您定义该方法时改变其行为。
def addresses_attributes =(id_and_attrs)
id_and_attrs.each do | id,attrs |
address = self.addresses.find(id)|| self.addresses.build(:id => id)
address.attributes = attrs
end
end
未经测试,所以你必须找出结果。特别是,如果地址是全新的,因为用户是新的,我不记得嵌套参数是如何不同的。
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.
fields_for
will work if you define addresses_attributes=
on User
. For some reason fields_for
actually changes its behavior if you define that method.
Here's an example implementation:
def addresses_attributes=(id_and_attrs)
id_and_attrs.each do |id, attrs|
address = self.addresses.find(id) || self.addresses.build(:id => id)
address.attributes = attrs
end
end
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.
这篇关于以Rails的形式处理MongoMapper EmbeddedDocument的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!