问题
So let's say we have a rails view with this code:
<h1>Users who have the <%= @title.name %> Title</h1>
<ul>
<% @title.users.each do |user| %>
<li><%= user.username %> <div class="rw-ui-container rw-urid-X"></div></li>
<% end %>
</ul>
And what we want to do is to automatically print this line:
<div class="rw-ui-container rw-urid-X"></div>
Right aside each username the loop throws at us BUT we want X to be a different unique random number each time...
How can this be accomplished?
回答1:
May be this solution can help you:
1. You can use user_id
as first part of the random X
to ensure that
another user doesn't have it
2. Second part is time in UTC format to set X
different each time
3. Third part is just a standart random func. You haven't use it if you want.
<h1>Users who have the <%= @title.name %> Title</h1>
<ul>
<% @title.users.each do |user| %>
<li><%= user.username %> <div class="rw-ui-container rw-urid-<%= "#{user_id}#{Time.now.utc.to_i}#{rand(100000)}".to_i %>"></div></li>
<% end %>
</ul>
回答2:
css_arr = ["rw-ui-container rw-urid-1","rw-ui-container rw-urid-2","rw-ui-container rw-urid-3"]
<div class="<%= css_arr.sample %>"></div>
回答3:
Well You could easily add a new field to user table call
uuid
or give it any name that you like and assign a unique id using the gem called uuid
This help ensure that you have uniqueness in X
section and also on refresh the value wont change as you mention in one of your comment
so here how your X
code would look like
<% @title.users.each do |user| %>
<li><%= user.username %> <div class="rw-ui-container rw-urid-<%=user.uuid %>"></div></li>
<% end %>
来源:https://stackoverflow.com/questions/11153244/rails-generate-unique-random-number-for-populating-a-css-class-string-how-to