[英]Include module contionally in Rails
考慮多個具有重疊字段和功能的 ActiveRecord 類,並且其中許多重疊字段具有相同的驗證。 我正在嘗試共享驗證,但如果滿足條件(基於模型的非重疊屬性之一),則不運行共享代碼。
class Book < ApplicationRecord
include SharedValidation
end
class Magazine < ApplicationRecord
include SharedValidation
end
module SharedValidation
extend ActiveSupport::Concern
include ActiveModel::Validations
validates_presence_of :name, :publisher, :author
end
所以假設Magazine.is_deleted
是一個 Magazine-only 字段,我們只想在 is_deleted 為false 時運行共享驗證。 關於如何在課堂上實現這一點的任何想法?
注意:我嘗試通過執行字段檢測和評估來修改模塊,但不確定這是否有意義或是否有效:
module SharedValidation
extend ActiveSupport::Concern
include ActiveModel::Validations
included do
proc do |rcd|
has_deleted_field = self.column_names.include?('is_deleted')
if (has_deleted_field && !rcd.is_deleted) || !has_deleted_field
validates_presence_of :name, :publisher, :author
end
end
end
end
看起來您可以將條件添加到驗證方法中(在 SharedModule 中),而不是有條件地包含模塊。
使用您的樣品:
class Book < ApplicationRecord
include SharedValidations
end
class Magazine < ApplicationRecord
include SharedValidations
end
module SharedValidations
extend ActiveSupport::Concern
include ActiveModel::Validations
def deleted
return unless self.class.column_names.include?("is_deleted")
is_deleted
end
included do
validates :name, :publisher, presence: true, unless: :deleted
end
end
Magazine 有name
、 publisher
和is_deleted
列。 Book 只有name
, publisher
沒有is_deleted
。
看起來這個設置有效。
irb> book = Book.new()
=> #<Book id: nil, name: nil, publisher: nil, created_at: nil, updated_at: nil>
irb> book.valid?
=> false
irb> book.errors.full_messages
=> ["Name can't be blank", "Publisher can't be blank"]
irb> magazine = Magazine.new
=> #<Magazine id: nil, name: nil, publisher: nil, is_deleted: nil, created_at: nil, updated_at: nil>
irb> magazine.valid?
=> false
irb> magazine.errors.full_messages
=> ["Name can't be blank", "Publisher can't be blank"]
irb> magazine.is_deleted=true
=> true
irb> magazine.valid?
=> true
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.