0
我遇到問題更新文檔及其嵌入式文檔一起去Sinatra 1.4.4和Mongoid 3.1.5。就目前而言,嵌入式文檔不會被修改,只需要嵌套的屬性並將它們添加到父級別。Sinatra + Mongoid更新嵌入式文檔
假設:
給定的形式,如:
<form action="/persons/edit/52cad9f0d2a57d2ded000070 method="post">
<input name="name" value="Some Guy" />
<input name="address[street]" value="Evergreen Street" />
<button type="submit">Save</button>
</form>
的模型,如:
class Person
include Mongoid::Document
include Addressable
accepts_nested_attributes_for :address
field :name, type: String
end
class Addressable
extend ActiveSupport::Concern
included do
embeds_one :address, class_name: 'Address', cascade_callbacks: true
end
end
class Address
include Mongoid::Document
field :street, type: String
before_save :strip_whitespace
def remove_whitespace
attributes.each do |attr_name, value|
next unless value.is_a? String
send("#{attr_name}=", value.strip.gsub(/\s(\s+)/, ' '))
end
end
end
的文件,如:
{
name: "Default Name",
address: {
_id: ObjectId("52fc501f266d9841d000007c"),
street: "Default Street"
},
}
最後,一路線如下:
post '/persons/edit/:id' do |id|
p = Persons.find(id)
p.update_attributes params
end
結果
我希望文檔落得爲:
{
name: "Some Guy", //this is okay
address: {
_id: ObjectId("52fc501f266d9841d000007c"),
street: "Evergreen Street"
}
}
而是使用結束:
{
name: "Some Guy", //this is okay
address: {
_id: ObjectId("52fc501f266d9841d000007c"),
street: "Default Street" //not changed
},
street: "Evergreen Street" //WTF?
}
我知道我做錯了什麼,但對於我的生活,我看不到什麼。我發現奇怪的是,如果我將表單上的name
屬性從使用括號更改爲點(例如address.street
),則更新可行,但Sinatra不會將該參數識別爲Hash
,而只是整個params
中的一個鍵。
有關如何解決此問題的任何想法?我錯過了什麼嗎?
感謝您的幫助!
將試試這個並報告回來,謝謝你的提示! – Roberto
這很好,我想我應該更仔細地閱讀文檔。德米特里,謝謝你! – Roberto