遍历视图中的参数数组

Iteration over array of params in view

我有一个 Sinatra 应用程序,我希望它显示参数对之间的交互列表。现在我只允许 2 个选择,但我想要一个可以允许任意多个选项的解决方案。

此代码 returns 需要在终端中进行交互,但我不知道如何在页面上显示它。建议?

<p><%= array = params.values.permutation(2).to_a.each {|a| a.sort! }.uniq! %></p>
<div><%= array.each do |a| p Aed.interactions(a[0], a[1]).humanize end %>

呈现一个 html 页面,注入一个变量的值,这与向控制台写入内容不同。将 p(print/put/printf) 语句放在视图文件中不会执行任何操作,将它放在 route/controller 中也会将其写入控制台,而不是浏览器。

如果您 运行 下面的代码并访问 http://locahost:4567/hello/15/male/kensington(主机和端口可能不同)

get '/hello/:age/:sex/:location' do 
 "Hello. I am a #{params[:sex]}. I am #{params[:age]} years old and I live in #{params[:location]}"
end

你会在浏览器上看到一个文本 window 之类的,

您好。我是男性。我今年 15 岁,住在肯辛顿

如果您有视图文件并想将一些变量传递给该视图,

get '/hello/:age/:sex/:location' do 
  @age = params[:age]
  @sex = params[:sex]
  @loc = params[:location]
  erb :hello 
end

样本hello.erb(假设你有这样的文件),

<p>Below table holds some info about King Matt the First</p>

<table>
  <tr>
    <td>Age</td>
    <td>Sex</td>
    <td>Location</td>
  </tr>
  <tr>
    <td><%= @age %></td>
    <td><%= @sex %></td>
    <td><%= @loc %></td>
  </tr>
</table>

当您访问localhost:4567/11/male/warsaw

您将看到包含该内容的页面。

关于您的代码,请使用 combination(2) 而不是 permutation(2).to_a {|a| a.sort! }.uniq!

2.3.1 :029 > a = [1,2,3].permutation(2).to_a.each {|a| a.sort! }.uniq!
 => [[1, 2], [1, 3], [2, 3]] 
2.3.1 :030 > b = [1,2,3].combination(2).to_a
 => [[1, 2], [1, 3], [2, 3]] 

最好不要使用数组作为变量名,但如果你坚持使用,你的代码应该写成在浏览器上打印一些东西window..

<div>
<% array.each do |a| %> 
<%= Aed.interactions(a[0], a[1]).humanize %> 
<% end %>
</div>

http://apidock.com/ruby/ERB

您还应该考虑将数据库查询迁移到 route/controller 块中。