ruby-on-rails - 在 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。
为什么在我尝试此操作时调用数组中的第一项有效,但在尝试遍历整个数组时却无效?
解决方案
好吧...如果您使用for循环。如果没有,您可能应该离开0..(@followers.length - 1)
,它会返回一个(undefined method
first_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 %>
推荐阅读
- reactjs - 我如何在 reactJS 上制作 lib 文件
- node.js - 使用 Express Nodejs 在浏览器中输出
- php - 遍历目录并使用 PHP 获取文件并将每个文件夹文件包装在 ul li 元素中
- django - 排除所有并保留一个 Django 查询
- javascript - VSCode HTML缩进,同一行结束标记
- azure-active-directory - Azure 托管服务标识:12 次后无法获取令牌
- python - 检查是一个字符串是二进制
- javascript - 如何删除特定列中的行边框?
- sql-server - 如何使用 ssis 包将 postgres 布尔值加载到 sql server
- c# - 在终结器中处置的资源与在处置中释放的资源有什么区别