Rails 控制台查询正常;但应用程序中的相同请求会产生错误
Rails Console queries working; but the same request in the app produces an error
我正在尝试弄清楚如何在 Rails 4.
中制作一个简单的应用程序
我有用户、个人资料和身份的模型。这些协会是:
用户
has_many :identities, dependent: :destroy
has_one :profile, dependent: :destroy
简介
belongs_to :user
身份
belongs_to :user
在控制台我可以写:
p = Profile.last
p.user.identities.map(&:provider).include?('facebook')
并且它正确地产生了 :false
的结果
当我尝试在配置文件辅助方法中编写以下内容时:
if @profile.user.identities.map(&:provider).include?('facebook')
我收到一条错误消息:
undefined method `user' for nil:NilClass
我在应用程序中有一个登录用户。我不明白为什么我在控制台中可以成功请求这个,但是我在应用程序中尝试时却出现错误。
谁能看出哪里出了问题?
你的 @profile
是 nil
。这就是发生错误的原因。
我假设您是从 show.html.erb
文件调用辅助方法。在 show.html.erb
文件中调用辅助方法,如:
<%= helper_method_name(@profile) %> # make sure your @profile is a `Profile` object
在profiles_helper.rb
def helper_method_name(profile)
if profile.user.identities.map(&:provider).include?('facebook')
// do something
end
end
我正在尝试弄清楚如何在 Rails 4.
中制作一个简单的应用程序我有用户、个人资料和身份的模型。这些协会是:
用户
has_many :identities, dependent: :destroy
has_one :profile, dependent: :destroy
简介
belongs_to :user
身份
belongs_to :user
在控制台我可以写:
p = Profile.last p.user.identities.map(&:provider).include?('facebook')
并且它正确地产生了 :false
的结果当我尝试在配置文件辅助方法中编写以下内容时:
if @profile.user.identities.map(&:provider).include?('facebook')
我收到一条错误消息:
undefined method `user' for nil:NilClass
我在应用程序中有一个登录用户。我不明白为什么我在控制台中可以成功请求这个,但是我在应用程序中尝试时却出现错误。
谁能看出哪里出了问题?
你的 @profile
是 nil
。这就是发生错误的原因。
我假设您是从 show.html.erb
文件调用辅助方法。在 show.html.erb
文件中调用辅助方法,如:
<%= helper_method_name(@profile) %> # make sure your @profile is a `Profile` object
在profiles_helper.rb
def helper_method_name(profile)
if profile.user.identities.map(&:provider).include?('facebook')
// do something
end
end