ruby-on-rails-5activemerchant

undefined method `each' for nil:NilClass (ActiveMerchant)


After filling payment information, when I click on 'place order' I get this error

NoMethodError in OrdersController#create

undefined method `each' for nil:NilClass

OrdersController

def create
 @order = Order.new(order_params)
 @order.add_line_items_from_cart(@cart)
 credit_card = ActiveMerchant::Billing::CreditCard.new(params[:credit_card])

 respond_to do |format|
  if @order.save
    Cart.destroy(session[:cart_id])
    session[:cart_id] = nil
    format.html { redirect_to category_url(Category.first), notice: 'Thank you for your order.' }
    format.json { render :show, status: :created, location: @order }
  else
    format.html { render :new }
    format.json { render json: @order.errors, status: :unprocessable_entity }
  end
 end
end

order model:

attr_accessor :card_no, :card_cvv, :expiry_date

I'm guessing i need to group :card_no, :card_cvv and :expiry_date in a data structure labelled 'credit_card' but I don't know how. Thanks!

Edit:

NoMethodError (undefined method `each' for nil:NilClass):

app/controllers/orders_controller.rb:32:in `new'

app/controllers/orders_controller.rb:32:in `create'

Rendering C:/RailsInstaller/Ruby2.2.0/lib/ruby/........


Solution

  • You need to get the params according to what you're sending from your form, so, if you want to access to them, you must take the params from the order root, that's to say, the card_no will be params[:order][:card_no], and this way all of them.

    And in order to make use of the ActiveMerchant gem and to create a new "CreditCard", you need to pass there your values received from the form, something like:

    credit_card = ActiveMerchant::Billing::CreditCard.new(
      :first_name         => params[:order][:first_name],
      :last_name          => params[:order][:last_name],
      :number             => params[:order][:card_cvv],
      :month              => params[:order][:month],
      :year               => Time.now.year+1, # documentation value
      :verification_value => '000' # documentation value
    )