[英]Why am I getting an “undefined method” error with my has_one relationship in rails?
我有一个页面可以输出系统中存在的所有用户配置文件。 以前它在工作,我什么都没改变,现在却不起作用。 告诉我,我有一个“ nil:NilClass的未定义方法`profile_name'”,但是我在应用程序的其他位置多次引用profile_name。 这是索引视图页面:
<% @profiles.each do |profile| %>
<%= link_to profile.user.inspect, profile_path(profile.user.profile_name) %><br><br>
<% end %>
这是配置文件模型:
class Profile < ActiveRecord::Base
belongs_to :user
end
这是用户模型:
class User < ActiveRecord::Base
has_one :profile
这是个人档案控制器:
def index
@profiles = Profile.all
end
另外,数据库中的概要文件表具有一列user_id。 另外,我检查了数据库,所有用户都有一个配置文件名称。 在个人资料页面上,我引用@ user.profile。(个人资料属性),因此我知道has_one / belongs_to关系正在起作用。 我不知道该怎么办。 请帮忙。
谢谢。
出于任何原因,您的profile.user
为nil
。 由于nil
没有定义.profile_name
方法,因此会出现错误。
我的猜测是@profiles
中有一个没有定义user_id
的配置文件。
您的所有个人档案都具有user_id
值吗? 您可能需要考虑执行以下操作,以验证所有概要文件都存在user_id
:
Profile.pluck :user_id
我怀疑配置文件对象/记录没有user_id
,因此通过profile.user.profile_name
遍历会出现nil类错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.