[英]i want to list all my users from the database, i am getting a strange error - undefined method `each'.What should i do?
這是列出我的用戶的代碼
<div>
<% @govornik.each do |g| %>
<p><%= g.name %></p>
<p><%= g.description %></p>
<% end %>
</div>
這是控制器的代碼
class GovorniciController < ApplicationController
def new
end
def show
@govornik = Govornik.new
end
end
Govornik 是我的模型這里是我的模型的代碼和該模型的遷移
class Govornik < ApplicationRecord
end
遷移代碼
class CreateGovorniks < ActiveRecord::Migration[5.2]
def change
create_table :govorniks do |t|
t.string :name
t.string :description
t.timestamps
end
end
end
問題結論:
我想顯示連接到模型 govornik 的數據庫表 Govornici 中的所有 mi 用戶,並且我從錯誤頁面中獲得以下錯誤圖像
為什么這是一個“奇怪的錯誤”? 這是一個完全預期的錯誤。 這個:
@govornik = Govornik.new
創造了一個新的Govornik
記錄。 並且,新的Govornik
記錄不包含方法each
。 因此,該錯誤正是您所期望的。
如果你想要一個所有Govornik
記錄的集合,那么你應該創建一個更像的變量:
@govorniks = Govornik.all
在這種情況下,變量@govorniks
(將是ActiveRecord::Relation
)將具有each
方法,您可以使用它來迭代所有記錄。
順便說一句,我建議您從控制台復制錯誤並將它們作為文本包含在您的問題中。 在某些設備上很難閱讀屏幕截圖。 而且,如果我們需要這樣做來幫助您解決問題,則無法復制和粘貼。 此外,屏幕截圖錯誤不會顯示整個堆棧跟蹤,這有時會有所幫助。
@jvillian 的回答是正確的。
def index
@govorniks = Govornik.all
end
下一次,你可以使用腳手架。 開始時創建控制器、模型和視圖要容易得多。 您可以學習從輸出中逆向工程代碼。
rails g scaffold Govornik name:string description:string
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.