3

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)='.

In my model:

class CartServer

  include ActiveModel::Validation

  include ActiveModel::Conversion

  extend ActiveModel::Naming

  attr_accessor :card_expiration_date

In view:

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]
)
georgebrock
  • 28,393
  • 13
  • 77
  • 72
loganathan
  • 5,838
  • 8
  • 33
  • 50

3 Answers3

3

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

There are two things here that are important:

  • 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.

  • 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",
    }
    

    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.

georgebrock
  • 28,393
  • 13
  • 77
  • 72
-2

How to set an attr_accessor date via Rails date_select and have Rails handle the multi-attributes automatically: https://gist.github.com/paulsturgess/5500858

Sergei Struk
  • 358
  • 4
  • 12
-2

attribute :card_expiration_date, Type::Date.new

kuboon
  • 9,557
  • 3
  • 42
  • 32