[英]Update all data of model in rails
For example we have:例如我们有:
class PublicLibrary < ActiveRecord::Base
has_many :books
end
class Book < ActiveRecord::Base
belongs_to :public_library
end
If we want do update all books in PublicLibrary, we can add to PublicLibrary model如果我们想更新 PublicLibrary 中的所有书籍,我们可以添加到 PublicLibrary model
accepts_nested_attributes_for :books, :allow_destroy => true, :reject_if=>:all_blank
And now we can do something like this现在我们可以做这样的事情
library=PublicLibrary.find(ID)
library.update_attributes(:books_attributes=>{<bunch of books here>})
And all related books will be updated, some books'll be removed and some new books will be inserted in table books并且所有相关书籍都将更新,一些书籍将被删除,一些新书籍将插入表格书籍
Now I have some model Book, that doesn't have relation with PublicLibrary:现在我有一些 model 书,与 PublicLibrary 没有关系:
class Book < ActiveRecord::Base
end
I have an admin panel that show all books in one big-big table and want to update/delete/insert new books just by one click, so I want something like我有一个管理面板,可以在一张大桌子上显示所有书籍,并且想要一键更新/删除/插入新书籍,所以我想要类似的东西
Book.bulk_update({...books...})
Or working with subset (don't sure is I really need it, but if we can do that...why not to know how?)或使用子集(不确定我是否真的需要它,但如果我们能做到……为什么不知道怎么做?)
books_to_update=Book.where(...).bulk_update({...books...})
Of course Book may have some nested models.当然 Book 可能有一些嵌套模型。
Do you have any ideas?你有什么想法? PS Currently I have only idea of having some parent and do update for it...
PS目前我只知道有一些父母并为它做更新......
your {...books...} hash either has multiple books in it for which you want你的 {...books...} hash 里面有你想要的多本书
books.each { |id, book| Book.find(id).update_attributes(book) }
or you want to do a real bulk update (meaning same update to all books in action) then you can use http://apidock.com/rails/ActiveRecord/Relation/update_all或者您想进行真正的批量更新(意味着对所有正在运行的书籍进行相同的更新),那么您可以使用http://apidock.com/rails/ActiveRecord/Relation/update_all
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.