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?
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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With