嘗試使用用戶 has_many polls/roles 創建投票應用程式,但投票有很多回答者,只有一個管理員。
用戶.rb
class User < ApplicationRecord
rolify
has_many :polls, dependent: :destroy, through: :roles, source: :resource, source_type: :Poll
end
民意調查.rb
class Poll < ApplicationRecord
resourcify
# has_many :users, through: :roles, class_name: 'User', source: :users
has_many :answerers, -> { where(:roles => {name: ::answerers}) }, through: :roles, class_name: 'User', source: :users
belongs_to :admin, -> { where(:roles => {name: :admin}) }, through: :roles, class_name: 'User', source: :users
end
繼續遇到以下錯誤:
Unknown key: :through. Valid keys are: :class_name, :anonymous_class, :primary_key, :foreign_key, :dependent, :validate, :inverse_of, :strict_loading, :autosave, :required, :touch, :polymorphic, :counter_cache, :optional, :default
該錯誤是由 poll.rb 中的這一行引起的:
belongs_to :admin, -> { where(:roles => {name: :admin}) }, through: :roles, class_name: 'User', source: :users
uj5u.com熱心網友回復:
您遇到了由混淆的belongs_tovs語意引起的經典誤解has_one。
Abelongs_to將外鍵列放在該模型表上。當您使用belongs_to :adminRails 時,假定您有polls.admin_id指向admins.id.
belongs_to關聯從來都不是間接的,因此沒有through:選擇。has_one做。
如果您想保證投票只能有一個管理員,您不想在這種特定情況下使用 Rolify,而是使用:
class Poll < ApplicationRecord
resourcify
# ...
belongs_to :admin, class_name: 'User'
end
這完全沒問題。雖然 Rolify 提供了一種方便的方式來添加角色,但并不是應用程式中的每個關聯都應該硬塞進去。直接鏈接比通過兩個連接表更有效,并提供只有一個值的保證。
雖然您可能在想“如果我只使用 has_one 會怎樣?”。has_one不保證民意調查只有管理員 - 它只是添加LIMIT 1到查詢中。
Rolify 使用 HABTMusers_roles連接表來連接用戶和角色,例如,您無法在不影響整個系統的情況下向該表添加唯一性約束。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/464556.html
上一篇:如何使用導軌進行接受和拒絕功能
