为什么我在轨道中的has_one关系出现"undefined method"错误?



我有一个页面,输出系统中存在的所有用户配置文件。 它以前工作过,我没有改变任何东西,现在它不起作用。 它告诉我我有"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关系正在发挥作用。 我不知道该怎么办。 请帮忙。

谢谢。

您的所有配置文件都有user_id值吗?您可能需要考虑执行以下操作来验证所有配置文件是否存在user_id

Profile.pluck :user_id

我怀疑配置文件对象/记录没有user_id,因此通过 profile.user.profile_name 遍历会导致 nil 类错误。

无论

出于何种原因,您的profile.user都是nil。 由于nil没有定义.profile_name方法,因此会出现错误。

我的猜测是@profiles中有一个配置文件没有定义user_id

最新更新