Activerecord Relationships: Can children access parents?

I am having trouble when using a child to reference the parent object
in a relationship, it always claims the parent is nil. I could easily
be doing something wrong as this is all hazy but I thought I’d ask if
anyone could see anything obvious:

I have two databases:

rulesets
id
name

races
id
name
ruleset_id

A race specifies it’s ruleset so, a ruleset can have many races, but
each race will have only 1 ruleset. I have specified a foreign key
relationship without a constraint (using mysql “foreign key
(ruleset_id) references rulesets (id)”) but my version of MySQL
doesn’t even enforce foreign keys so that shouldn’t help much. In the
models I have:

class Ruleset < ActiveRecord::Base
has_many :races

class Race < ActiveRecord::Base
belongs_to :rulesets

Then in the controller I have:

@races = Race.find( :all )

And finally in the view:

<% @races.each do |r| %>

<%= @r.ruleset.name %>

And it complains that ruleset is not a valid method for races. The
book I have on Ruby only talks about doing this sort of access in one
direction (i.e. ruleset.races. not
races.ruleset.) so I’m not even sure if it’s possible to
have a child accessing the values of it’s parent. But if it is, what
am I doing wrong here?

Thanks in advance!!

Chris

restart your server?

I just restarted and that did not solve the problem. I’m using
Webbrick and I’m in development mode, so I’m hoping everything gets
reloaded each run… but nevertheless, it was worth a shot.

Chris

On Sep 10, 9:23 am, Dustin A. [email protected]

class Race < ActiveRecord::Base
belongs_to :rulesets

I think this should be singular:
belongs_to :rulesets

This worked. I changed both references to singular and it works now.
Funny, my Rails programming text’s examples show using the plural form
of the DB. I even checked that to make sure it was plural and not
singular.

Anyway,

belongs_to :ruleset
has_many :races

…did the trick. Thanks so much!

Chris

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs