在我的index.html.erb
文件中,我收到了一个未定义的电子邮件方法.我进入rails控制台并尝试运行User.first.email,它运行良好.我尝试取出电子邮件并运行link.user
,这也很有用.当用户绑定到链接并且用户有电子邮件时,我不确定为什么电子邮件是未定义的.我正在寻找一些可能出错的建议.
Index.html.erb
<%= link.user.email %>
迁移的架构已经运行
create_table "users", force: :cascade do |t| t.string "email", default: "", null: false
楷模:
class Link < ActiveRecord::Base belongs_to :user validates :user, presence: true acts_as_votable attr_accessor :avatar mount_uploader :avatar, AvatarUploader end class User < ActiveRecord::Base has_many :links acts_as_voter devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable end
链接控制器:
class LinksController < ApplicationController before_filter :authenticate_user!, except: [:index, :show] def index @links = Link.all end def show @link = Link.find(params[:id]) end def new @link = Link.new end def edit end def create @link = Link.new(link_params) if @link.save redirect_to root_path else render 'new' end end private def link_params params.require(:link).permit(:title, :url, :avatar, :user_id) end end
错误信息:
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]] (0.1ms) begin transaction (0.1ms) rollback transaction Rendered links/_form.html.erb (2.7ms) Rendered links/new.html.erb within layouts/application (3.8ms) Completed 200 OK in 505ms (Views: 143.6ms | ActiveRecord: 0.4ms)
K M Rakibul .. 6
undefined method `email' for nil:NilClass link.user.email
您收到此错误link.user
是nil
因为某些链接,因此它调用nil.email
并失败并显示上述错误消息.
您可以使用try来摆脱这个问题,如下所示:
<%= link.user.try(:email) %>
这样,你的程序将无法即使崩溃link.user
是nil
对一些案件.
undefined method `email' for nil:NilClass link.user.email
您收到此错误link.user
是nil
因为某些链接,因此它调用nil.email
并失败并显示上述错误消息.
您可以使用try来摆脱这个问题,如下所示:
<%= link.user.try(:email) %>
这样,你的程序将无法即使崩溃link.user
是nil
对一些案件.