简体   繁体   中英

How do I use simple_form with a plain Ruby class?

I have a credit card class and I'd like to use the simple_form f.input method on the various attributes for use with validations, etc, but I'm getting errors about model_name. Is there a simple way to do this?

= simple_form_for @credit_card, url: join_network_path do |f|
    .payment-errors
  = f.input :card_number
  = f.input :cvc
  = f.input :expiry_month
  = f.input :expiry_year
  = f.submit 'Join Network'

You'll need to conform to the ActiveModel API...

Effectively:

class CreditCard
  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  def initialize(attributes = {})
    attributes.each do |name, value|
      send("#{name}=", value)
    end
  end

  def persisted?
    false
  end
end

Some background:

  1. http://yehudakatz.com/2010/01/10/activemodel-make-any-ruby-object-feel-like-activerecord/
  2. http://railscasts.com/episodes/219-active-model

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM