我创建了一个名为 Category 的模型,我在 seed.db 文件中填充了数据
,如下所示:Category.create([{
title: 'Glutein-free hoagie with tofu',
price: Faker::Number.decimal(2)
}])
Category.create([{
title: 'Hoagie with Pesto and Mozzarela',
price: Faker::Number.decimal(2)
}])
Category.create([{
title: 'Hoagie with fried veggies and soy meat',
price: Faker::Number.decimal(2)
}])
Category.create([{
title: 'Protein bread with sweet potato, carrots and vegan mayo',
price: Faker::Number.decimal(2)
}])
现在,我希望在我的网页上显示这些结果,所以我通过 rout 将其与 categories.index.html 文件连接.db如下所示:
Rails.application.routes.draw do
resources :order_items
resources :orders
resources :categories
resources :users
resources :customers
root to: 'categories#index'
get 'home/index'
end
尽管如此,当我使用 localhost 时,我看到 8 个元素而不是 4 个元素,其他 4 个元素是我创建的元素的副本。最重要的是,重复项具有不同的值,这意味着它们可能在内部存储两次?这是页面上显示的内容:
Categories
Title
Glutein-free hoagie with tofu 29.84 Show Edit Destroy
Hoagie with Pesto and Mozzarela 54.11 Show Edit Destroy
Hoagie with fried veggies and soy meat 39.61 Show Edit Destroy
Protein bread with sweet potato, carrots and vegan mayo 83.89 Show Edit Destroy
Glutein-free hoagie with tofu 81.57 Show Edit Destroy
Hoagie with Pesto and Mozzarela 34.42 Show Edit Destroy
Hoagie with fried veggies and soy meat 16.71 Show Edit Destroy
Protein bread with sweet potato, carrots and vegan mayo 30.13 Show Edit Destroy
New Category
这是索引.html文件:
<p id="notice"><%= notice %></p>
<h1>Categories</h1>
<table>
<thead>
<tr>
<th>Title</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @categories.each do |category| %>
<tr>
<td><%= category.title %></td>
<td><%= category.price %></td>
<td><%= link_to 'Show', category %></td>
<td><%= link_to 'Edit', edit_category_path(category) %></td>
<td><%= link_to 'Destroy', category, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= link_to 'New Category', new_category_path %>
如果帖子太长,我提前道歉,但我不确定如何发布代码,因为有许多类相互连接。
编辑:我通过在 rails 控制台中调用删除表中的所有数据来解决此问题Category.delete_all
看起来你跑了两次rake db:seed
,这就是为什么你用不同的价格重复入场的原因。您可以安全地删除它们,它应该可以正常工作。
最好的方法
在种子.rb
10.times do
Category.create([{
title:Faker::Food.dish,
price: Faker::Number.decimal(2),
}])
end
然后在终端中
rake db:seed
它将创建 10 个类别数据