我有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
和每个已保存的books
集user
保存/更新多个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
?
答案 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_id
和editor_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
我不认为这里需要多态性。