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 [email protected] %>
<%= @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 [email protected] %>
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?
<% @followers.each do |follower| %>then you would just use the piped local variablefollowerinside the block. Also just because@followers.firsthas a profile does not mean that@followers.forty_twodoes<% @followers.each do |follower| %>as I said in the question but it returned the same thing.profile. Try this and seeUser.find_by(id: params[:user_id]).followers.left_joins(:profile).where(profiles: {id: nil})#<ActiveRecord::AssociationRelation []>. I seeded every profile and user in the database together, so all users present have profiles.profilereturnsnil. Try changing toprofile&.first_nameand see where the empty result is.