在 Ruby on Rails 中验证虚拟属性 [英] Validation of virtual attributes in Ruby on Rails

查看:25
本文介绍了在 Ruby on Rails 中验证虚拟属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Rails (3.2.0) 上运行 Ruby (1.9.3) 并且在验证虚拟属性时遇到问题.

I am running Ruby (1.9.3) on Rails (3.2.0) and having a problem with the validation of virtual attributes.

我有一个 Flight 模型,它代表一个航班,其中包括一个代表出发和到达机场的属性.

I have a Flight model that represents a flight which, among others, has an attributes that represents the airport of departure and arrival.

因为用于选择机场的 select 可能很大,所以我选择了一个自动完成解决方案,它工作得非常好.我正在使用 before_validation 回调来正确填充机场的实际 ID:

Because the select for selecting an airport is potentially huge, I opted to go for an autocomplete solution, which is working perfectly fine. I am using a before_validation callback to properly populate the actual ID of the airport:

before_validation do
  self.departure_airport = Airport.find_by_long_name(departure_airport_name)
  self.arrival_airport = Airport.find_by_long_name(arrival_airport_name)
end

然而,问题是,当用户输入数据库中不存在的机场名称时,提交失败,因为任一机场的 ID 都是 nil.伟大的.然而,不好的是,这种验证失败并没有反映在表单上,​​因为从技术上讲,它是另一个字段的输入:

The problem is, however, that when the user enters the name of an airport that does not exist in the database, the commit fails because the ID of either airport is nil. Great. What's not great, however, is that this validation failure is not reflected on the form because technically, it's the input for another field:

validates :departure_airport, :arrival_airport presence: true

attr_accessor :departure_airport_name, :arrival_airport_name

<%= f.input :departure_airport_name %>
<%= f.input :arrival_airport_name %>

before_validation 回调中将机场名称转换为 ID 是否正确?如果是这样,我怎样才能让验证错误显示在机场的虚拟名称属性上?

Is this even the way to properly go about, transforming the name of the airport into an ID in the before_validation callback? And if so, how can I get the validation errors to show up on the virtual name attribute of the airport?

推荐答案

我认为您使用 before_validation 回调是正确的.

I think you are going the right way with the before_validation callback.

您可以像验证每个普通属性一样验证虚拟属性.所以你所需要的只是模型中的一些验证.试试这个:

You can validate virtual attributes like every normal attribute. So all you need is just some validation in the model. Try this:

validates :departure_airport, presence: true
validates :arrival_airport, presence: true

这应该向对象错误添加一个错误,并且该错误应该显示在您的表单中...

this should add an error to the objects errors and the error should be displayed in your form...

这篇关于在 Ruby on Rails 中验证虚拟属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆