简体   繁体   中英

Iterating through array of models with complex relations in Ruby

So I have done this kind of thing countless times in the past, but I can't seem to wrap my head around why this isn't working this time. I am fairly new to RoR and I was using some new relations in my model, that is the only reason I can think of so far.

User model has the following relations

  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

I am trying to list the followers of any one particular user, but the names are stored in the user profile. I have tried doing this:

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 %>

So, I initially tried for.each before trying a ordinary for loop. But it always returns

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 %>

However, putting <%= @followers.first.profile.first_name %> returns the first_name of the first follower.

Why does calling the first item in the array work when I am trying this but not when I am trying to iterate over the entire array?

Well... if you use a for-loop. You should probably go from 0..(@followers.length - 1) if not, it'll return a (undefined method first_name' for nil:NilClass)` error like you are seeing.

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

or better yet, use the for.each and send the error. if there is any.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM