不合理的未定义方法"电子邮件"



我正在构建一个模仿Evernote的repo,并且我已经建立了模型和各自列之间的关系。其中,我依靠User模型中的列email来识别用户。

但是,当我尝试在index.html中打印<%= note.user.email %>时。例如,我得到nil的未定义方法email错误。我不明白,我已经建立了有效的has_manybelongs_to,email也是一个实际的列。note源自控制器中的实体变量@note(其他字段有效),我不明白哪个链接是错误的。

这是schema

的一部分
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

这是User模型的一部分

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

this is 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>

未定义的方法' email' for nil:NilClass">

这个错误意味着你正在寻找一个nilClass对象上的email方法,这意味着你的note.user是nil。

Rails找不到任何与注释相关的用户。您可以首先检查您的note是否为user

您还应该检查您的Note模型中是否有user_id列,这是使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>

最新更新