【问题标题】:Why am I getting an "undefined method" error with my has_one relationship in rails?为什么我在 rails 中的 has_one 关系出现“未定义方法”错误?
【发布时间】:2013-11-04 21:07:14
【问题描述】:

我有一个页面可以输出系统中存在的所有用户配置文件。它以前工作,我没有改变任何东西,现在它不工作。它告诉我,我有“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.(profile 属性),因此我知道 has_one/belongs_to 关系有效。我不知道该怎么办。请帮忙。

谢谢。

【问题讨论】:

    标签: ruby-on-rails methods belongs-to has-one database-relations


    【解决方案1】:

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

    Profile.pluck :user_id
    

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

    【讨论】:

      【解决方案2】:

      无论出于何种原因,您的profile.usernil。由于nil 没有定义.profile_name 方法,您会得到错误。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-02
        • 1970-01-01
        • 2017-10-21
        • 2014-01-06
        • 1970-01-01
        相关资源
        最近更新 更多