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
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 ofnil#id
will again raise an error.
I hope you get the point!
+10