简体   繁体   English

Rails / Ruby:获取信用卡的最后4位数字

[英]Rails/Ruby: Get Last 4 Digits of Credit Card

I know I've seen a few similar questions, but none of the solutions have worked for me. 我知道我已经看到了一些类似的问题,但是没有一个解决方案对我有用。

I'm sending a 16 digit number to my Credit Card controller, but I only want the last four. 我正在向我的信用卡控制器发送一个16位数字,但是我只想要最后四个。 I've been trying every version of [-4..-1] to [14-16] to last(4) and I still get the same error: too many digits. 我一直在尝试从[-4 ..- 1]到[14-16]的每个版本到last(4),但我仍然遇到相同的错误:位数过多。 This is the line of code I have right now (:last_4 is sent to controller with 16 digits) : 这是我现在拥有的代码行(:last_4以16位数字发送到控制器):

credit_card_params[:last_4 => credit_card_params[:last_4].last(4)]

The field is an integer field. 该字段是整数字段。 Here is a sample input: 这是一个示例输入:

1234567890987654

And that should produce this: 那应该产生这个:

7654

What am I doing wrong? 我究竟做错了什么?

UPDATE: 更新:

I very much appreciate all of your responses. 我非常感谢您的所有答复。 It u=turns out this is in fact a string. u =证明这实际上是一个字符串。 In any case, I've been pulling my hair out over this. 无论如何,我一直在为此扯头发。 Still doesn't work! 还是不行! This is my code, and my controller is still complaining that there's too many chars: 这是我的代码,我的控制器仍在抱怨字符太多:

ccNum=credit_card_params[:last_4]
ccNum = ccNum[-4..-1] 
credit_card_params[:last_4 => ccNum]
@credit_card = CreditCard.new(credit_card_params)
respond_to do |format|
  if @credit_card.save #HERE IS THE ERROR!

and this is the code in the form: 这是形式的代码:

<%= f.label :last_4, "Credit Card Number" %><br>
<%= f.number_field :last_4 %>

leaves string 1234123412341235 unchanged, with this error message: 保留字符串1234123412341235不变,并显示以下错误消息:

1234123412341235 is out of range for ActiveRecord::Type::Integer with limit 4 1234123412341235超出ActiveRecord :: Type :: Integer的范围,限制为4

If anyone can figure this out I would really appreciate it. 如果有人能弄清楚这一点,我将非常感激。

Consider this: 考虑一下:

cc = 1111222233334444 # 16 digits in int
cc = cc.to_s # as a string now
cc = cc[-4..-1] # as a string "4444"
cc = cc.to_i #now as a int 4444

Or in just one line 或仅一行

cc = cc.to_s[-4..-1].to_i

Try this: 尝试这个:

last_4 = credit_card_params[:last_4].to_s.last(4)

credit_card_params[:last_4] = last_4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM