如何使用活动模型为 date_select 下拉菜单定义虚拟属性 [英] How to define virtual attribute for date_select drop menu using active model
问题描述
我在我的应用程序中使用活动模型进行付款流程,但我无法为信用卡到期日期添加字段,因为它会引发如下错误未定义的方法`card_expiration_date(3i)='.
I am using active model for payment process in my application , but i am not able to add field for credit card expiration date, since it throws error as below undefined method `card_expiration_date(3i)='.
在我的模型中:
class CartServer
include ActiveModel::Validation
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_accessor :card_expiration_date
在视图中:
f.date_select(
:card_expiration_date,
:add_month_numbers => false,
:discard_day => true,
:start_year => (Date.today.year-10),
:end_year => (Date.today.year+10),
:order=>[ :month,:year]
)
推荐答案
这样的事情将在 Rails 6 中工作:
Something like this will work in Rails 6:
class CartServer
include ActiveModel::Model
include ActiveModel::Attributes
include ActiveRecord::AttributeAssignment
attribute :card_expiration_date, :date
end
这里有两件事很重要:
使用
:date
类型声明attribute
.在 ActiveRecord 模型中,此类型信息来自数据库模式,但由于我们使用的是 ActiveModel,因此需要显式声明它.
Declaring the
attribute
with type:date
. In an ActiveRecord model this type information comes from the database schema, but since we're using ActiveModel we need to explicitly declare it.
包括 ActiveRecord::AttributeAssignment
以获得对多部分参数分配的支持.表单中的参数如下所示:
Including ActiveRecord::AttributeAssignment
to get support for multi-part parameter assignment. The params from the form will look something like this:
{
"card_expiration_date(1i)" => "2020",
"card_expiration_date(2i)" => "12",
"card_expiration_date(3i)" => "31",
}
我们从 ActiveModel::Model
获得的 ActiveModel::AttributeAssignment
模块不知道如何将其转换为日期,因此我们需要引入更多全功能的 ActiveRecord
版本.
The ActiveModel::AttributeAssignment
module we get from ActiveModel::Model
doesn't know how to convert this into a date, so we need to pull in the more fully featured ActiveRecord
version instead.
这篇关于如何使用活动模型为 date_select 下拉菜单定义虚拟属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!