1

我有以下設置:Rails的update_attributes方法爲特定的關聯模型

class Post < ApplicationRecord 
    has_many :comments, inverse_of: :post, dependent: :destroy 
    accepts_nested_attributes_for :comments 
end 

class Comment < ApplicationRecord 
    belongs_to :post 
end 

如果我打電話post.update_attributes(post_params)

哪裏post_params如下:創建

post_params = { 
    "content"=>"Post something", 
    "comments_attributes"=>{ 
    "0"=>{ 
     "content"=>"comment on something" 
    } 
    } 
} 

註釋新評論並與該帖子相關聯。

有沒有辦法讓我們update_attributes的帖子,並仍然更新與帖子相關的特定評論?

也許是這樣的:

post_params = { 
    "content"=>"Post something", 
    "comments_attributes"=>{ 
    "0"=>{ 
     "id"=>"1", #if the id exist update that comment, if not then add a new comment. 
     "content"=>"comment on something" 
    } 
    } 
} 

於是我可以打電話post.update_attributes(post_params)並採取更新的優勢accepts_nested_attributes_for的。

如果這不可行,更新相關評論來更新帖子的最佳方法是什麼?

任何幫助將不勝感激。

回答

1

只要您維護模型的正確模型ID,就可以更新提供的記錄。

所以,如果postcomments使用標識4,5,6,你可以提交:

post.update(comments_attributes: [{id: 4, content: 'bob'}] 

這將更新現有Comments.find(4)記錄(前提是它成功驗證)。

但是,如果您傳遞的ID不適用於屬於該帖子的評論,則會拋出異常。

+0

謝謝!所以看起來我在我的問題中寫了一些東西。當我嘗試這樣的事情時,它不起作用。但事實證明,我沒有在我的Strong Params中設置身份證。再次感謝。 :-) – user2517182