Undefined id method for # <ActiveRecord :: Relation []>

I cannot get id value from model.

My code is:

session["game_space"] = params[:game_space_id] @player_space = PlayerSpace.where(game_space_id: session["game_space"], user_id: current_user.id) session["player_space"] = @player_space.id #<<<<===== The error occurs here redirect_to "show",:id => @player_space.id 

Error message:

 Error: undefined method `id' for #<ActiveRecord::Relation []> 

Can you help me?

+6
source share
3 answers

Problems:

  • Here, the sentence returns the active object of the record relation, which is a kind of array (collection). Therefore, you need to select an object to call the id method on it.

    @player_space = PlayerSpace.where (game_space_id: session ["game_space"], user_id: current_user.id) .first

  • There is no row / object in your query results / collection. Therefore, calling #first will return zero. Thus, the result of nil#id will again raise an error.

I hope you get the point!

+10
source

You are trying to get id in ActiveRecord Relation. Try the following:

@player_space = PlayerSpace.where(game_space_id: session["game_space"], user_id: current_user.id).first

Then get the identifier @player_space

+2
source

You get the ActiveRecord::Relation class back, not the model object. You can get the identifier from the element in relation. If you are sure to get exactly one element back, you can simply do:

 PlayerSpace.where(game_space_id: session["game_space"], user_id: current_user.id).first 
+2
source

Source: https://habr.com/ru/post/978410/


All Articles