0

I have a credit card number field on a table. For <%= f.text_field :credit_number %>, I want to show it with some format like 'xxxx xxxx xxxx xxxx' instead of 'xxxxxxxxxxxxxxxx'. But I don't want to save the space with the number in the DB.

For now I don't care about inputting but only displaying.

What's the best way to accomplish it?

Thanks.

Sam

1 Answer 1

1

text_field not good for credit card number use <input type="number"> instead.Try create helper, for render in view like this:

=> "xxxxxxxxxxxxxxxx".chars.each_slice(4).map(&:join)*' '
=> "xxxx xxxx xxxx xxxx"

in view use placeholder:

<%= f.text_field :credit_number, placeholder: "xxxx xxxx xxxx xxxx" %>

From comment:

add before_create block to model in models/user.rb:

before_create do
  credit_number.split(' ').join if credit_number
end

Now before create (write to db) credit_number string join.

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

2 Comments

Thank you for the answer. However, you misunderstood my question. I know how to change the string. But I want to save the data without format while showing with format.
@SamKong add before_create block to you model. Look update answer

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.