使用循环。生成简单的兑换码。很有趣。
loop do
puts (('A'..'Z').to_a + (0..9).to_a).shuffle[0,12].join
sleep 1
end
那么怎么进行生成点击按钮新建兑换码就直接在表格进行填写生成的验证码呢?
在一个表格中增加默认值 value
然后引入数据即可,明确一个概念,在erb文件中使用rb代码使用<% %> 或者<%= %> 加上等号就是可以输出数据,不加等号就是不输出数据。
<%= form_for @blog do |form| %>
<div class="title">
<label>
标题:
<%= form.text_field :title, :value => "#{(('A'..'Z').to_a + (0..9).to_a).shuffle[0,12].join}" %>
</label>
</div>
<% end %>
,然后使用我们需要的数据生成即可,刷新页面,兑换码会自动变化
Recognized Tags
ERB recognizes certain tags in the provided template and converts them based on the rules below:
<% Ruby code -- inline with output %>
<%= Ruby expression -- replace with result %>
<%# comment -- ignored -- useful in testing %>
% a line of Ruby code -- treated as <% line %> (optional -- see ERB.new)
%% replaced with % if first thing on a line and % processing is used
<%% or %%> -- replace with <% or %> respectively
All other text is passed through ERB filtering unchanged.
View的基本概念和用法
View在MVC中,一直是最简单的概念. 大家要分分钟入门.
视图在Rails中, 就是 .html.erb 文件. 我们原则上把跟HTML有关的东西,都写在 视图中.
每个视图都要由controller触发. 所有的视图文件,都放在: app/views/
目录下. 例如: app/views/books/new.html.erb
这是Rails的约定 .
最基本用法
下面是一个最简单的erb文件:
<p>当前时间是: <%= Time.now %></p>
它会直接被转换成下面的HTML:
<p>当前时间: 2016-10-08 21:01:35 +0800</p>
<% %>
与 <%= %>
的区别
<% %>
表示仅运行代码, 例如: <% a = 1 %>
<%= %>
表示,不但运行, 而且把结果渲染到html中. 例如: <%= Time.now %>