Ruby on rails 向控制器中的数组添加指向方法的链接
我在rails 4应用程序控制器中有一个索引方法,看起来像:Ruby on rails 向控制器中的数组添加指向方法的链接,ruby-on-rails,ruby,arrays,Ruby On Rails,Ruby,Arrays,我在rails 4应用程序控制器中有一个索引方法,看起来像: def index @products = Product.all @headers = @products.map(&:data).flat_map(&:keys).uniq @product_data = @products.map{ |product| product[ :data ].values } end 因此,@product_data的结尾类似于: [["Table", "$199.
def index
@products = Product.all
@headers = @products.map(&:data).flat_map(&:keys).uniq
@product_data = @products.map{ |product| product[ :data ].values }
end
因此,@product_data的结尾类似于:
[["Table", "$199.99", "blue"], ["Book", "$9.99", "green"]]
在我看来,我把所有这些都放在了一个无序的列表中。但是现在我想要一个链接到每个产品的编辑和删除页面。如何将其包含在数组中,以便在查看页面上显示每个产品的链接?您可以将
product\u id
添加到product[:data].值数组的结果中。然后将该product\u id
用作product
url\u助手的参数
@product_data = products.map{ |product| product[ :data ].values.unshift(product.id) }
这将为您提供类似于:
[[1, "Table", "$199.99", "blue"], [2, "Book", "$9.99", "green"]]
我看到那里没有使用@product\u data
。为什么不能在index.html.erb
中的表格中显示数据,然后可以循环浏览每个产品,这样每个产品都会显示编辑和删除链接。假设您有名称
,price
和color
属性为您的产品型号,就这样做吧
在index.html.erb:
<table border=1>
<tr>
<th>Product Name</th>
<th>Product Price</th>
<th>Product Color</th>
<th></th>
<th></th>
</tr>
<% @products.each do |p| %>
<tr>
<td><%=p.name %></td>
<td><%=p.price %></td>
<td><%=p.color %></td>
<td><%=link_to 'Edit', :action => "edit", :id => p.id %></td>
<td><%=link_to 'Delete', :action => "delete", :id => p.id, :confirm => "Are you sure?" %></td>
</tr>
<% end %>
</table>
品名
产品价格
产品颜色
“编辑”,:id=>p.id%>
“删除”,:id=>p.id,:confirm=>“确定吗?”%>
注意:
这只是另一种方法