Jon
Jon

Reputation: 3985

Simple database association issue in rails

Newbie rails developer here.

I'm having an issue trying to setup some very simple database associations in a new rails project.

In my database I have two tables, one called "Games" and one called "Onlines". Here's what's in them right now

Game.first
#<Game id: 1, name: "Game 1", description: "This is a cool game", url: "http://domain.com">

Online.first
#<Online id: 1, game_id: 1, now: 222>  

I'm trying to setup a simple association so I can grab the number of users online by doing something like...

Game.find(1).onlines.now 

In my game.rb and online.rb models I have

belongs_to :online 

and

belongs_to :games

accordingly.

When I try and run Game.find(1).onlines.now in the rails console I get the following error.

NoMethodError: undefined method `onlines' for #<Game:0x00000101654300>
from /Users/Jon/.rvm/gems/ruby-1.9.2-p180@rails3tutorial/gems/activemodel-3.0.6/lib/active_model/attribute_methods.rb:367:in `method_missing'
from /Users/Jon/.rvm/gems/ruby-1.9.2-p180@rails3tutorial/gems/activerecord-3.0.6/lib/active_record/attribute_methods.rb:46:in `method_missing'
from (irb):5
from /Users/Jon/.rvm/gems/ruby-1.9.2-p180@rails3tutorial/gems/railties-3.0.6/lib/rails/commands/console.rb:44:in `start'
from /Users/Jon/.rvm/gems/ruby-1.9.2-p180@rails3tutorial/gems/railties-3.0.6/lib/rails/commands/console.rb:8:in `start'
from /Users/Jon/.rvm/gems/ruby-1.9.2-p180@rails3tutorial/gems/railties-3.0.6/lib/rails/commands.rb:23:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'

Am I missing something ridiculously obvious here? I've tried everything I can think of.

Upvotes: 1

Views: 112

Answers (1)

Jordan Running
Jordan Running

Reputation: 106027

You should have

has_many :onlines

in your Game model, not belongs_to.

Upvotes: 4

Related Questions