在我把這個作爲一個bug發佈到rails團隊之前,我想看看我是否做了可能導致這種行爲的錯誤。具體來說,has_many關聯的:autosave屬性似乎不按照文檔工作。:在Rails 2.3.4中破壞has_many關聯的自動保存屬性?
僅供參考,這裏是最新的API文檔: http://api.rubyonrails.org/classes/Acti ... ation.html
看看「一對多例」部分。我在測試應用程序中完全複製了代碼,並且它不適合我。具體來說,父對象被更新,但子對象不是。
我的架構如下:
create_table :posts do |t|
t.string :title
t.timestamps
end
create_table :comments do |t|
t.text :body
t.integer :post_id
t.timestamps
我的型號如下:
class Post < ActiveRecord::Base
has_many :comments, :autosave => true
end
class Comment < ActiveRecord::Base
belongs_to :post
end
在控制檯中,我運行以下命令(帖子和評論的對象已經在數據庫在這一點上):
post = Post.find(1)
post.title # => "The current global position of migrating ducks"
post.comments.first.body # => "Wow, awesome info thanks!"
post.comments.last.body # => "Actually, your article should be named differently."
post.title = "On the migration of ducks"
post.comments.last.body = "Actually, your article should be named differently. [UPDATED]: You are right, thanks."
post.save
post.reload
但是,這是我得到的輸出:
post.title # => "On the migration of ducks"
post.comments.last.body # => "Actually, your article should be named differently."
而且,看在日誌中,這是唯一的更新語句我看到:
帖子消息(0.6ms)UPDATE 「上崗」 SET 「的updated_at」=「2010-01-18 23:32: 39',「title」='關於遷移的鴨子'WHERE「id」= 1
所以看起來保存並沒有級聯到評論對象,這似乎很明顯地打破了我的觀點。我已經在運行2.3.4的兩個不同系統上嘗試了這一點,並且行爲是可重複的。
雖然這是一個奇怪的部分:如果我在嘗試設置該值之前先調用「post.comments」,它會正常工作!確切的說:
post.title = "On the migration of ducks"
post.comments #Note that this line was not called above
post.comments.last.body = "Actually, your article should be named differently. [UPDATED]: You are right, thanks."
post.save
post.reload
現在輸出給了我正確的結果:
post.title # => "On the migration of ducks"
post.comments.last.body # => "Actually, your article should be named differently. [UPDATED]: You are right, thanks."
而且日誌包含正確的更新:
評論更新(0.3ms的)UPDATE 「意見」 SET 「updated_at」='2010-01-18 23:44:43',「body」='其實,你的文章應該有不同的命名。 [已更新]:你說得對,謝謝。'在哪裏「ID」= 2
所以這真的看起來打破了我。我猜測這是處理對象引用的一個問題,也就是說,一旦對象是分配集合的一部分,它就可以很好地保存,但當它從數據庫中作爲單個對象提取時,它不會保存。但在我將這個問題提交給Rails團隊之前,我想看看是否有其他人遇到了這個問題,或者如果我只是在做一些完全骨頭的事情,而我沒有看到,因爲我已經花了整整一天的時間。
我不認爲你可以郵寄一份錯誤的Rails 2.3.4,因爲它甚至不是2.3系列的最後一個穩定版本。有可能是在AutosaveAssociation模塊中修復了一個錯誤。我甚至懷疑他們會在2.3.11中對此進行修正。 – 2011-05-31 18:47:24