0

I am new at ruby and rails and on my studies I've created this Payment Types array of my Order..

class Order < ActiveRecord::Base

  PAYMENT_TYPES = [{:id => "check", :name => "Check"}, {:id => "credit_card", :name => "Credit card"}, {:id => "purchase_order", :name => "Purchase order"}]

and I would like to use this way

<%= f.select :pay_type, Order::PAYMENT_TYPES.each {|order| [order.name, order.id]}, :prompt => 'Select a payment method' %>

but I'm getting this error

undefined method `name' for {:id=>"check", :name=>"Check"}:Hash

what is wrong?

1 Answer 1

2

In your each block, the variable order is being filled each time with a hash. Therefore you need to access it like a hash with order[:name] and order[:id] instead of .name and .id.

Edit

Also, for maintainability, you may want to create a separate PaymentType model. This will give you much more power and flexibility. With your current method, what happens if you want to add or remove a payment type later? You'll have to edit the source code. What if you only want certain payment methods to be available for certain transactions?

Sign up to request clarification or add additional context in comments.

2 Comments

thanks vpsz! but tell me which method should I call instead of .each that returns only that array I need like [['check', 'Check], ['credit_card', 'Credit Card']] ??
Ah, I didn't even notice that error before. You want to use the 'map' method. each simply calls the block for every item in the array (like a foreach loop), whereas map runs the block on each of the elements then returns an array of the results (basically transforms the array using the function you provide in the block). Using .each and .map will be like 95% of what you do in RoR.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.