Reputation: 59
I have an issue where my ActiveRecord::Relation isn't working I have 3 Db's Users,Games,Achievements The relation defined between them is such
Users
has_many :games
Games
belongs_to :user
has_many :achievements
Achievements
belongs_to :game
The problem is when i try to call
Game.where(:appid => game["appid"]).achievements.new
it gives me and error saying that
undefined method `achievements' for #<Game::ActiveRecord_Relation:0x730f9f8>
I am running on Ruby on Rails 4.1.8 and I have no clue why this is happening (I do have the belongs_to :game,index: true column in my Achievements table I can't think of why its not working)
Upvotes: 1
Views: 1394
Reputation: 331
The answer is in the exception. #where returns an ActiveRecord_Relation, not a Game, even if there is only one Game in the relation. So you really have an enumerable. i.e:
puts Game.where(:appid => game["appid"]).first.achievements.new
If you just want the first game that meets the criteria, you can use find_by
Game.find_by(:appid => game["appid"])
but I am not sure that's what you are looking for
Upvotes: 0
Reputation: 10825
Probably, you should select one model
Game.where(:appid => game["appid"]).first
and then get relational models
.achievements.new
Upvotes: 0
Reputation: 536
You are getting an association here:
Game.where(:appid => game["appid"])
... this is realized as an array of objects (even if the sql returns no records, then it is still an array, although it is empty).
You need to select one of them ... probably the first, like this:
Game.where(:appid => game["appid"]).first.achievements.new
Or you can run through the values:
Game.where(:appid => game["appid"]).each { |game| game.achievements.new }
or some such.
Upvotes: 1