首页 > 解决方案 > 在 Ruby 中遍历具有复杂关系的模型数组

问题描述

所以我过去无数次做过这种事情,但我似乎无法理解为什么这一次不起作用。我对 RoR 相当陌生,我在我的模型中使用了一些新的关系,这是迄今为止我能想到的唯一原因。

用户模型有以下关系

  has_one :profile

  has_many :follower_relationships, class_name: "Follow", foreign_key: "following_id"
  has_many :followers, through: :follower_relationships, source: :follower

  has_many :following_relationships, class_name: "Follow", foreign_key: "user_id"
  has_many :following, through: :following_relationships, source: :following

我正在尝试列出任何特定用户的关注者,但名称存储在用户个人资料中。我试过这样做:

In the conroller: 

def followers
  @followers = User.find_by(id: params[:user_id]).followers
end

In the html.erb file:

<% for i in 0..@followers.length %>
   <%= @followers[i].profile.first_name %>
<% end %>

所以,我最初for.each在尝试普通的 for 循环之前尝试过。但它总是返回

ActionView::Template::Error (undefined method `first_name' for nil:NilClass):
    2:
    3:
    4: <% for i in 0..@followers.length %>
    5: <%= @followers[i].profile.first_name %>
    6: <% end %>

但是,put 会<%= @followers.first.profile.first_name %>返回first_name第一个跟随者的 the。

为什么在我尝试此操作时调用数组中的第一项有效,但在尝试遍历整个数组时却无效?

标签: ruby-on-rails

解决方案


好吧...如果您使用for循环。如果没有,您可能应该离开0..(@followers.length - 1),它会返回一个(undefined methodfirst_name' for nil:NilClass)` 错误,就像您看到的那样。

<% for i in 0..(@followers.length-1) %>
   <%= @followers[i].profile.first_name %>
<% end %>

或者更好的是,使用 for.each 并发送错误。如果有的话。

<% @followers.each do |f| %>
  <%= f.profile.first_name %>
<% end %>

推荐阅读