… used in orderscontroller#new to create an array, which is used in a select method of a form field in views, which is supposed to add a new order
Hullo there,
So my error is this
Routing Error
undefined local variable or method `array_of_payment_types’ for #
Now, I’ve got this select field for a form to submit a new order, but my browser won’t load the page with the form:
<div class="field">
<%= f.label :pay_type %><br />
<%= f.select :payment_type_id, Order::PAYMENTS_TYPES,
:prompt => 'Select a payment method' %>
</div>
This is using an array that I am trying to create twice:
class Order < ActiveRecord::Base
...
belongs_to :payment_type
**PAYMENT_TYPES = array_of_payment_types**
validates :name, :address, :email
validates :pay_type, :inclusion => { :in => PAYMENT_TYPES }
...
**def array_of_payment_types
PaymentType.pluck(:pay_type_name)
end**
end
and here:
class OrdersController < ApplicationController
...
def new
@cart = current_cart
if @cart.line_items.empty?
redirect_to store_url, :notice => "Your cart is empty"
return
end
**@PAYMENT_TYPES = array_of_payment_types**
@hide_checkout_button = true
@order = Order.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @order }
end
end
...
end
while the method to create the array, which “plucks” the entries from the :pay_type_name column Payment_Type table, is declared both in order.rb and the ApplicationController, here:
class ApplicationController < ActionController::Base
protect_from_forgery
private
...
def array_of_payment_types
PaymentType.pluck(:pay_type_name)
end
end
Now I am trying to use the same process as other pieces of my application, just replicating stuff I have already done. For example, in OrdersController#new I’ve got
@cart = current_cart
current_cart is a method declared in the ApplicationsController and it works. So why doesn’t array_of_payment_types also work?
Thanks for your help in advance 🙂
Further information…
What I am trying to do with this is to create a new order, using a form, and one of the fields in the form enters a “pay_type” (or payment type in English). I want to present the user with options which is a list “plucked” from the entries in the PaymentType table, column :pay_type_name (I may be repeating myself, but no harm). But the new Order is created after the Order#new action, which is where I have created the array. Where/how should I create the array?
def array_of_payment_typesin your Order class defines an instance method and you are trying to use it as a class method.I’d just define array_of_payment_types as a class method instead and call Order.array_of_payment_types instead of the constant ARRAY_OF_PAYMENT_TYPES in your view.
You can always cache it in the class method, there’s no need to use a constant for this.
But, consider leaving the responsibility for the payment type array in the PaymentType class. The Order class shouldn’t be the point of contact to retrieve data which is clearly under the control of another class.