Joh*_*ent 2 ruby-on-rails ruby-on-rails-4
我有2个模型通过关联与has_many连接.
Book可以有很多作者和Author很多书.
在AuthorsController在update从API的行动,我得到作者的ID和书籍ID数组Parameters: {"books"=>"3,4,5", "id"=>"1"},我需要与他们更新作者的书籍.实现这一目标的最佳方法是什么?
我试过author.books << Book.where(id: params[:books])但问题在于,如果一本书已经出现在作者的书中,它将会被复制.
最有效的方法是使用:has_many Association Reference.vide:Rails 4指南
4.3.1 Methods Added by has_many
Run Code Online (Sandbox Code Playgroud)
声明has_many关联时,声明类会自动获得与该关联相关的16个方法:
collection(force_reload = false)
collection<<(object, ...)
collection.delete(object, ...)
collection.destroy(object, ...)
collection=(objects)
collection_singular_ids
**collection_singular_ids=(ids)**
collection.clear
collection.empty?
collection.size
collection.find(...)
collection.where(...)
collection.exists?(...)
collection.build(attributes = {}, ...)
collection.create(attributes = {})
collection.create!(attributes = {})
Run Code Online (Sandbox Code Playgroud)
例:
author.books << Book.where(id: params[:books])
Run Code Online (Sandbox Code Playgroud)
执行不必要的数据库查询。
您可能需要删除数据库中已有的书籍
books_array = params[:books].split(',') - author.books.pluck(:id)
books_array.each do |a|
author.author_books.build(book_id: a)
end
# I assumed author_books is the join table
Run Code Online (Sandbox Code Playgroud)