我正在構建一個模仿 Evernote 的 repo,并且我已經建立了模型與其各自列之間的關系。其中,我是依靠模型User中的email這一列來識別用戶的。
但是,當我嘗試<%= note.user.email %>在 index.html.erb 中列印時,我收到“nil:NilClass 的未定義方法 `email'”錯誤。我不明白,我已經建立了有效的has_manyand belongs_to,并且email也是一個實際的列。note來自控制器中的物體變數@note(其他欄位有效),我不明白哪個鏈接是錯誤的。
這是架構的一部分
create_table "users", force: :cascade do |t|
t.string "nickname"
t.string "password"
t.string "email"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
這是模型用戶的一部分
class User < ApplicationRecord
validates :nickname, presence: true
validates :email, presence: true
validates :password, presence: true, confirmation: true
before_create :encrypt_password
has_many :notes
這是模型注
class Note < ApplicationRecord
validates :title, presence: true
validates :content, presence: true
default_scope { where(deleted_at: nil) }
belongs_to :user
end
這是 NotesController 的一部分
def index
@notes = Note.includes(:user).order(id: :desc)
end
這是 index.html.erb
<table>
<tr>
<td>Author</td>
<td>Title</td>
<td>Actions</td>
<% @notes.each do |note| %>
<tr>
<td>
<%= note.user.email %>
</td>
<td>
<%= link_to note.title, note_path(note) %>
</td>
<td>
<%= link_to "TO EDIT", edit_note_path(note) %>
</td>
<td>
<%= link_to "TO DELETE", note_path(note), method: 'delete', data: { confirm: "確定嗎?" } %>
</td>
</tr>
<% end %>
</table>
uj5u.com熱心網友回復:
nil:NilClass 的未定義方法‘email’”
此錯誤意味著您正在尋找emailnilClass 物件上的方法,這意味著您note.user是 nil。
Rails 找不到任何與筆記相關的用戶。您可以先檢查您的noteas是否為user.
此外,您應該檢查user_id您的 Note 模型中是否有一個列,它是使belongs_to關系正常作業所必需的。您可能在筆記遷移中做了類似的事情:
create_table "notes", force: :cascade do |t|
t.belongs_to :user
...
end
如果您希望您的視圖繼續呈現并在注釋沒有任何用戶時忽略錯誤,您可以這樣做。
<% if note.user.present? %>
<td>
<%= note.user.email %>
</td>
<% end %>
甚至使用安全導航運算子,但它有其優點和缺點
<td>
<%= note.user&.email %>
</td>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/465707.html
標籤:轨道上的红宝石
