0

I have a constant called PAYMENT_METHODS in venue.rb.

PAYMENT_METHODS = {'Visa' => 1, 'MasterCard' => 2, 'American Express' => 3, 'Diners' => 4, 'JCB' => 5, 'Bankomat' => 6, 'sodexo' => 7, 'MA-Gutscheine' => 8 }

You can check/uncheck multipe payment types in a form (payment_options is a string):

<%= hidden_field_tag "venue[payment_options][]", nil %>
<% Venue::PAYMENT_METHODS.each do |key, value| %>
  <%= f.check_box :payment_options, {:multiple => true}, value %>
  <%= label_tag key %>
<% end %>

Now I want to save the values to the single Database Column payment_options, e.g. [1,3,5]. No matter what I check, it always saves 0. What am I doing wrong? I am using PostgreSQL.

Thanks in advance

1
  • You try to save a string to an int column? Commented Mar 19, 2012 at 11:17

1 Answer 1

2

You have several options here.

String column

Serialize this to a string and save to a VARCHAR column. There are many ways.

Examples:

update orders set payment_options = '1,2,3'; -- comma separated list    
update orders set payment_options = '{"visa": 1, "amex": 1}'; -- json object

Integer column

Store your selections as bits in a single int column.

Example:

VISA = 0x01
MASTERCARD = 0x02
AMEX = 0x04
DINERS = 0x08

update order set payment_options = #{VISA | MASTERCARD}; -- int value 3
update order set payment_options = #{MASTERCARD | DINERS}; -- int value 10

Then later you can check the value like this

def visa?
  (payment_options & VISA) == VISA
end

Flags and bitwise operations can be a little hard for you, if you never used them. Comma-separated list is probably the easiest choice.

Array column

Apparently, there are arrays in PostgreSQL, but I don't know much about this DB. Two previous options are universal and work in any database.

Many-to-many relationship

This had been covered zillion times. Keywords:

has_and_belongs_to_many
has_many :through
Sign up to request clarification or add additional context in comments.

2 Comments

thx! One general question: Do you think this is the right way to store payment types? I also thought about a PaymentTypemodel and a has_many_and_belongs_to_manyrelationship, but I think that is overkill...
Depends on how you are going to use it. As far as I understand your intentions, yes, it would be an overkill.

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.