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
的。
如果這不可行,更新相關評論來更新帖子的最佳方法是什麼?
任何幫助將不勝感激。
謝謝!所以看起來我在我的問題中寫了一些東西。當我嘗試這樣的事情時,它不起作用。但事實證明,我沒有在我的Strong Params中設置身份證。再次感謝。 :-) – user2517182