Rails 5.1:多态关联创建/更新记录,其中包含保存在Join表中的其他数据

时间:2017-08-17 08:02:27

标签: ruby activerecord ruby-on-rails-5.1

我有polymorphic association,看起来像这样:

class Permission < ApplicationRecord
  belongs_to :permitable, polymorphic: true, optional: true
  belongs_to :user, optional: true

  enum status: {creator: 1, editor: 2}
end

class User < ApplicationRecord
  has_many :permissions, class_name: 'Permission'
end

class Book < ApplicationRecord
  has_many :permissions, class_name: 'Permission', as: :permitable, dependent: :destroy
  has_many :users, class_name: 'User', through: :permissions
end

我需要为users和每个已保存的booksuser保存/更新多个permission.status

让我们说book=Book.first我需要添加:

1)user=User.find(2) permission.creator

2)user=User.find(1) permission.editor

在理想世界中,我需要在一个查询中执行此操作。 我该怎么办?谢谢!

更新

目前我可以这样做:

def create
  Book.create(book_params)
end

private

def book_params
  params.require(:book).permit(:name, {user_ids[]})
end

这会在Book中创建记录并在Permission中添加记录,但不会在status设置记录。

可能不是Permission模型的最佳示例 - 例如,它可能令人困惑。我应该将其更改为其他内容吗?

更新2

我在accepts_nested_attributes_for模型中添加了Book

class Permission < ApplicationRecord
  belongs_to :permitable, polymorphic: true, optional: true
  belongs_to :user

  enum status: {creator: 1, editor: 2}
end

class User < ApplicationRecord
  has_many :permissions, class_name: 'Permission'
end

class Book < ApplicationRecord
  has_many :permissions, class_name: 'Permission', as: :permitable, dependent: :destroy
  accepts_nested_attributes_for :permissions
  has_many :users, class_name: 'User', through: :permissions
end

然后在我的控制器中:

def create
  Book.create(:name, permissions_attributes: [{user_id: "1", status: :creator},
                                              {user_id: "2", status: :owner}])
end

private

def book_params
  params.require(:book).permit(:name, {permissions_attributes[:user_id, :status]})
end

如何动态创建一些循环来做create

1 个答案:

答案 0 :(得分:0)

如果每个book只能有一个创建者和一个编辑器,那么您可以这样做:

class User < ApplicationRecord
  # Maybe you'd like to define e.g. `created_books` and `edited_books`?
  has_many :books
end

class Book < ApplicationRecord
  belongs_to :creator, class_name: 'User'
  belongs_to :editor, class_name: 'User'
end

如果图书可以包含一个创建者和多个编辑器,那么您可以这样做:

class User < ApplicationRecord
  # Maybe you'd like to define e.g. `created_books` and `edited_books`?
  has_many :books
end

class Book < ApplicationRecord
  belongs_to :creator, class_name: 'User'
  has_many :editors, through: :book_editors
end

class BookEditor
  belongs_to :editor, class_name: 'User'
  belongs_to :book
end

创建图书时,传递creator_ideditor_id / editor_ids(如果它是has_many关系):

def create
  Book.create(book_params)
end

private

def book_params
  params.require(:book).permit(:name, :creator_id, editor_ids:[])
end

我不认为这里需要多态性。