【问题标题】:How to access attributes of associated resource in view through Devise's user model?如何通过 Devise 的用户模型访问视图中关联资源的属性?
【发布时间】:2023-03-03 05:19:27
【问题描述】:

我在尝试使用 Devise 在视图中显示用户配置文件属性时遇到问题。这只是为了显示值,我什至还没有尝试更新它,所以我认为不需要强参数。

这是我的模型:

# user.rb
class User < ActiveRecord::Base
  has_one :profile
end

# profile.rb
class Profile < ActiveRecord::Base
  belongs_to :user
end

这是我的控制器:

# users_controller.rb
class Admin::UsersController < AdminController
  def index
    @users = User.all.order('id ASC')
  end
end

这是我的看法:

# index.html.erb
<% if @users.present? %>
  <p><%= @users.first.profile.first_name %></p>

  <ul>
    <% @users.each do |user| %>
      <li><%= user.profile.first_name %></li>
    <% end %>
  </ul>
<% end %>

现在,虽然“each”循环外的&lt;%= @users.first.profile.first_name %&gt; 运行良好并返回值,但循环内的&lt;%= @users.first.profile.first_name %&gt; 返回以下错误:

NoMethodError: undefined method `first_name' for nil:NilClass

我得出的结论是,这取决于设计以及它如何允许您访问其自己的控制器之外的任何关联记录。作为记录,我为其他资源尝试了相同的代码,它按预期工作。

对此的任何帮助将不胜感激!

【问题讨论】:

  • 我认为这与设计无关,自然的解释是您的users 表中至少有一行 not 有对应的profiles 表中的行。使用 ActiveRecord,您可以通过 User.all.to_a.select { |u| u.profile.nil? } 找到这些
  • 当然!谢谢@gregates,我不敢相信我没想到。

标签: ruby-on-rails ruby ruby-on-rails-4 model-view-controller devise


【解决方案1】:

您循环通过users 并调用.profile.first_name,但您的一些用户没有.profile,即nil,这就是您收到的原因:

NoMethodError: nil:NilClass 的未定义方法 `first_name'

简单替换

<li><%= user.profile.first_name %></li>

<li><%= user.profile.try(:first_name) %></li>

如果用户的.profile 不存在,.try 将返回 nil,而不是引发异常

或者自己处理/显示一些信息:

<li><%= user.profile.present? ? user.profile.first_name : "Profile doesn't exist" %></li>

【讨论】:

  • 谢谢@rustam-a-gasanov,这很有帮助!这让我觉得我真的应该在我的代码中引入更多的条件和回退。
猜你喜欢
  • 2017-02-06
  • 2014-04-27
  • 2013-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-28
  • 1970-01-01
相关资源
最近更新 更多