1

In my application I have model User which like every model in Rails application has an id. And the question how can I customize this id to show it in the view in format not 1 but #0001. Is there any way to do it with using yml files?

Mohamed Yakout
  • 2,868
  • 1
  • 25
  • 45
Mateusz Urbański
  • 7,352
  • 15
  • 68
  • 133
  • why do you need it to be yaml files? can you show us what you've tried in the view-code so far (even if it isn't working)? – Taryn East Aug 21 '14 at 07:04
  • I don't try even this to do because I want to ask more experienced developers how to this. I think about yml files because it need to have prefix to be configurable without changing application code. For example: "CC0001" can in future change to "BB0001" – Mateusz Urbański Aug 21 '14 at 07:10
  • Hi, but sorry, that isn't usually how Stack Overflow works. We generally expect you to have tried it yourself, and then we help you fix your code... – Taryn East Aug 21 '14 at 07:14

3 Answers3

2

In the case you only plan to have less than 10000 users you can generate such strings by

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.

Christian Rolle
  • 1,664
  • 12
  • 13
1

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:

#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

Community
  • 1
  • 1
Richard Peck
  • 76,116
  • 9
  • 93
  • 147
  • 1
    It will work because I'm not changing user id in db. I only have this id in proper format to show in the view but thanks. – Mateusz Urbański Aug 21 '14 at 11:35
  • @Rich Peck: Since he wants to use the identifier in the view it is not a appropriate solution to put the logic into the model. It is representation stuff and belongs into the view (no other kind of representation than the HTML view needs the identifier). If you really do not want the logic in a view helper, I would rather agree to follow the decorator pattern and put the logic into a decorator. – Christian Rolle Aug 23 '14 at 09:32
  • Valid point - it's still a viable alternative to your solution though, whether it's 100% viable is another matter – Richard Peck Aug 23 '14 at 10:07
0

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

en:
  customer_prefix: "CC"
Mateusz Urbański
  • 7,352
  • 15
  • 68
  • 133