[英]validate presence of virtual attribute
I have custom action called add_roles in a controller and a related form view with a virtual attribute called :role_name. 我在控制器中有一个名为add_roles的自定义操作,并且具有一个名为:role_name的虚拟属性的相关表单视图。 I want to validate the presence of :role_name but it doesn't work:
我想验证:role_name的存在,但是不起作用:
This is the controller: 这是控制器:
Class StaffsController < InheritedResources::Base
def roles
@staff=Staff.find params[:id]
end
def add_roles
@staff=Staff.find params[:id]
role_name=params[:staff][:role_name] #this field must be present
@staff.add_role Role.find(role_name).name
redirect_to staff_path(@staff)
end
end
This is the model: 这是模型:
class Staff < ActiveRecord::Base
attr_accessible :email, :name, :surname
attr_accessor :role_name
validates_presence_of :role_name
validate do |staff|
if staff.role_name.blank?
staff.errors[:base] << "INVALID"
end
end
end
This is the view: 这是视图:
<%= simple_form_for @staff, url: :add_roles_staff do |f| %>
<%= f.input :role_name, as: :select, collection: Role.global %>
<%= f.button :submit %>
<% end %>
The correct behavior is if I don't select the select box :role_name the form shows me an error, but now it isn't working. 正确的行为是,如果我不选择选择框:role_name,该表单将显示一个错误,但现在不起作用。 The form doesn't show me any error.
表格没有显示任何错误。
check out our staff model to see if validation is working if triggered by hand: 查看我们的员工模型,看看是否通过手动触发验证是否有效:
s = Staff.new
s.valid?
s.role_name='role'
s.valid?
my guess is this works. 我的猜测是这样。 if that is the case your validation never triggered, probably because you dont save the model (as you only change a virtual attribute).
如果是这样,您的验证就不会触发,可能是因为您没有保存模型(因为您仅更改了虚拟属性)。 so my guess is just trigger validation explicitly.
所以我的猜测只是明确地触发验证。
However there is such a fundamental flaw in your code, that validation not working seems to be a minor problem: You should make the association between staff and his role explicitly on the database. 但是,您的代码中存在这样一个根本性的缺陷,即验证不起作用似乎是一个小问题:您应该在数据库中显式地创建职员及其角色之间的关联。 At thge moment the virtual attribute will not survive a request/response lifecycle.
此刻,虚拟属性将无法在请求/响应生命周期中生存。 As soon as you redirect out of the controller, that change is forever lost.
重定向到控制器后,该更改将永远丢失。
HTH HTH
and by the way validates_presence_of :role_name
does what you define below again: 并通过
validates_presence_of :role_name
再次执行您在下面定义的操作:
validate do |staff|
if staff.role_name.blank?
staff.errors[:base] << "INVALID"
end
end
so just delete that code 所以只需删除该代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.