Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I can't get id value from a model.

My code:

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 on this?

like image 690
Christiano Matos Avatar asked Nov 19 '14 15:11

Christiano Matos


2 Answers

Problems:

  • Where clause returns active record relation object which is a kind of array (collection). So you have to pick the object to call the id method over it.

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

  • Your query results/collection doesn't have any row/object. So calling #first will return nil. So as a result nil#id will cause error again.

Hope you get the point!

like image 181
Rubyrider Avatar answered Oct 15 '22 21:10

Rubyrider


You are trying to get an id on an ActiveRecord Relation. Try this:

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

Then get the id of @player_space

like image 30
aspencer8111 Avatar answered Oct 15 '22 20:10

aspencer8111