[英]ArgumentError: wrong number of arguments (1 for 2) for update method in rails
[英]Mongoid / Moped update an embedded document - ArgumentError - wrong number of arguments (2 for 1)
我在更新Ruby / Sinatra應用程序中的嵌入式文檔時遇到問題。 我試圖在更新語句中使用位置運算符“ $”,以便從嵌入式數組中選擇正確的文檔。 但這會引發“ ArgumentError-錯誤的參數數量(2為1)”錯誤。
一個帶有硬編碼數組索引的簡單更新語句可以正常工作。 因此,也許Mongoid / Moped不支持位置運算符嗎?...雖然從我的看到,看起來應該如此。
有誰知道最好的方法是什么? 還有其他方法可以確定子文檔索引,而無需在我的控制器中使用Ruby遍歷它們的全部內容-這是計划B,但似乎很不可靠!...
這是我的基本設置:我有“客戶” ...
class Customer
include Mongoid::Document
field :customer_name, type: String
embeds_many :contacts
attr_accessible :customer_name
end
...帶有嵌入式“聯系人” ...
class Contact
include Mongoid::Document
field :first_name, type: String
attr_accessible :first_name
embedded_in :customer
end
在我的控制器中,我獲得了兩個客戶的._ids(pk)和要更新的特定嵌入式文檔(contact_pk):
Customer.update(
{
"_id" => Moped::BSON::ObjectId(pk),"contacts._id" => Moped::BSON::ObjectId(contact_pk)
},
{
$set => {"contacts.$.first_name" => "Bob" }
}
)
update
類方法實際上是偽裝的Customer.with_default_scope.update
,這意味着update
實際上是Mongoid::Criteria
的update
方法, 它看起來像這樣 :
# Update the first matching document atomically.
#
# @example Update the first matching document.
# context.update({ "$set" => { name: "Smiths" }})
#
# @param [ Hash ] attributes The new attributes for the document.
#
# @return [ nil, false ] False if no attributes were provided.
#
# @since 3.0.0
def update(attributes = nil)
update_documents(attributes)
end
注意,它僅需要一個attributes
參數嗎? 那解釋了錯誤信息。 大概您期望update
的方式與在MongoDB Shell或JavaScript接口中的方式相同。
首先,你需要找到感興趣的文檔,然后調用update
上:
Customer.where('_id' => Moped::BSON::ObjectId(pk), 'contacts._id' => Moped::BSON::ObjectId(contact_pk))
.update($set => { 'contacts.$.first_name' => 'Bob' })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.