gpt4 book ai didi

ruby-on-rails - 显示委托(delegate)属性的验证错误

转载 作者:行者123 更新时间:2023-12-04 03:36:11 24 4
gpt4 key购买 nike

我有以下内容(其中 Venue 是 Actor 的 CTI 后代):

class Actor < ActiveRecord::Base
has_one :profile, validate: true, autosave: true
end

class Venue < ActiveRecord::Base
...
%w{description address website phone}.each do |attr|
delegate attr.to_sym, "#{attr}=".to_sym, to: :profile!
end

def profile!
actor.profile || actor.build_profile
end
...
end

我将这些委托(delegate)属性的字段直接包含在 Venue 表单中。当这些属性之一未通过验证时,我所看到的只是顶部的通知,而不是该字段周围的包装器。我想这一定是因为 Venue 实例的错误散列中的键与属性名称不完全匹配,被设置为 :"actor.profile.website" 而不仅仅是 :website

有什么方法可以使这些错误正确显示吗?

编辑

这是表格:

<%= simple_form_for @venue do |f| %>
<%= f.error_notification %>

<%= f.input :name %>
<%= f.input :address, required: true %>
<%= f.input :phone %>
<%= f.input :website %>
<%= f.input :members, collection: [], class: "form_tag" %>
<%= f.input :tag_list, as: :string, class: "form_tag", hint: t("misc.hint.tag"),
input_html: { "data-pre" => @venue.tag_list.map {|t| { id: t, name: t }}.to_json } %>
<%= f.input :description, as: :text, input_html: {rows: 6, cols: 53, class: "form_tag"} %>

<div class="actions center">
<%= f.submit class: "btn btn-success" %>

最佳答案

module OtherValidation
extend ActiveSupport::Concern

module ClassMethods
def delegate_with_validations(*attr_names)
options = attr_names.extract_options!
delegate *attr_names, options
attr_names.each {|a| validate_using(options[:to], a)}
end

def validate_using(target, *args)
options = args.extract_options!
args.each do |attr_name|
class_eval <<-EOV
dup = #{target}._validators[:#{attr_name}].dup
validate do
dup.each do |v|
validator = v.dup
validator.attributes.delete(:#{attr_name})
validator.attributes << :#{options[:to]||attr_name}
validator.validate(self)
end
end
EOV
end
end
end

end

现在在 Venue 模型中:

class Venue < ActiveRecord::Base
include OtherValidation
delegate_with_validations :website, :to => :profile!
end

# venue = Venue.new(:website => nil)
# venue.valid? # Profile validates presence of :website
#=> false
# venue.errors
#=> #<ActiveModel::Errors....., @messages={:website=>["can't be blank"]}>

更新:

对于任何自定义属性:

class Venue < ActiveRecord::Base
include OtherValidation
attr_accessor: title

validate_using("Profile", :website, :to => :title)
end

# :website validation behavior constraints to :title attribute

# venue = Venue.new(:title => nil)
# venue.valid? # Profile validates presence of :website
#=> false
# venue.errors
#=> #<ActiveModel::Errors....., @messages={:title=>["can't be blank"]}>

config/initializers/other_delegation.rb

module OtherValidation
...
end

ActiveSupport.on_load :active_record do
include OtherValidation
end

关于ruby-on-rails - 显示委托(delegate)属性的验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14001353/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com