简体   繁体   English

在Ruby on Rails中自定义呈现对象id的格式

[英]Customize format of presenting objects id in Ruby on Rails

In my application I have model User which like every model in Rails application has an id. 在我的应用程序中,我有模型用户,就像Rails应用程序中的每个模型都有一个id。 And the question how can I customize this id to show it in the view in format not 1 but #0001. 问题是如何自定义此ID以在格式中显示它而不是1而是#0001。 Is there any way to do it with using yml files? 使用yml文件有什么办法吗?

In the case you only plan to have less than 10000 users you can generate such strings by 如果您计划的用户数少于10000,则可以生成此类字符串

module UsersHelper
  def format_id user_id
    "##{user_id.to_s.rjust(4, '0')}"
  end
end

and in the view: 并在视图中:

<%= format_id user.id %>

But please also think about the format of your idea whenever the users id is higher than 9999. 但是,只要用户ID高于9999,也请考虑您的想法的格式。

Getter 消气

This might not work because you're changing the primary_key (which is a core feature of ActiveRecord / relational databases), but I'd recommend setting a specific getter for your request: 这可能不起作用,因为您正在更改primary_key (这是ActiveRecord /关系数据库的核心功能),但我建议您为您的请求设置特定的getter

#app/models/user.rb
Class User < ActiveRecord::Base
   def id
     "#{self[:id].to_s.rjust(4, '0')}" #-> from tobago's answer
   end
end

This will allow you to call @user.id and have #000x returned as the id, although the actual id attribute will still remain as 1 etc 这将允许您调用@user.id并将#000x作为id返回,尽管实际的id属性仍将保持为1

Answer is: 答案是:

I create an helper: 我创建了一个帮手:

  def format_id customer_id
    "#{t('customer_prefix')}#{customer_id.to_s.rjust(5, '0')}"
  end

and store customer_prefix in en.yml 并将customer_prefix存储在en.yml中

en:
  customer_prefix: "CC"

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

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