当前位置: 动力学知识库 > 问答 > 编程问答 >

ruby on rails - undefined method `name' for nil:NilClass. Can't find @followed.name but @followed is set

问题描述:

I'm trying to show a user, another user's information. (The users are 'friends')

I'm getting:

NoMethodError in Users#show_follow

undefined method `name' for nil:NilClass

because of this bit of code:

<%= @followed.name %>

I can't work out why the code can't find @followed as it's been assigned in the controller as I have done throughout the app. @active_relationship seems to be being assigned as it should. binding.pry wont open here either, again not sure why. Any ideas why I can't get @followed.name to show the name of the user being followed?

show_follow.html.erb:

<%= @active_relationship %>

<%= @followed.name %>

user_controller:

 def showf

if params[:active_relationship]

@active_relationship = current_user.active_relationships.find_by(params[:active_relationship])

@followed = @active_relationship.followed

else

"No relationship found"

end

end

user/model:

has_many :active_relationships, class_name: "Relationship",

foreign_key: "follower_id",

has_many :following, -> { where(relationships: { state: "accepted" } ) }, through: :active_relationships, source: :followed

relationship/model:

belongs_to :follower, class_name: "User"

belongs_to :followed, class_name: "User"

EDIT:

implemented the answer code from @choco and got binding.pry to work in the view. Outputs:

params:

=> {"active_relationship"=>"28", "action"=>"show_follow", "controller"=>"users"}

current_user:

User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1

=> #

@followed:

=> nil

@active_relationship:

=> nil

Why is @active_relationship nill when it's been set from the params that are proven to be there??

网友答案:

Change this:

def showf
    if params[:active_relationship]
      @active_relationship = current_user.active_relationships.find_by(params[:active_relationship])
     @followed = User.find(@active_relationship.followed_id).name 
     @profile = Profile.find_by_user_id(@followed.id) will give u the object of profile table
    else 
      "No relationship found"
    end
end

This will give you expected output.

分享给朋友:
您可能感兴趣的文章:
随机阅读: