Question

I have two tables: demographics and races. Each Demographic needs to have one Race. I have created a foreign key in the demographics table for race_id. Here are the models:

class Demographic < ActiveRecord::Base
  has_one :race
end

class Race < ActiveRecord::Base
  belongs_to :demographic
end

The view correctly pulls a list of races from the races table. I think the problem is in my Demographics controller. Please see the code in this error image:

error http://www.imageurlhost.com/images/bywqencxhmpjtx02laji.png

What is odd is that @demographic['race_id'] always retuns nil eventhough the dump has a value.

rails = v4.0.2
ruby = v2.0.0
psql = v9.1

Was it helpful?

Solution

It's because, as you noted, @demographic['race_id'] is nil. This results in the following code 'Demographic was successfully updated' + nil, which if you try in irb will fail in the same way. It is expecting a string to concatenate, and gets nil, instead. You could solve it like this 'Demographic was successfully updated' + tmp.to_s, this "Demographic was successfully updated #{ tmp }" or this 'Demographic was successfully updated' << tmp.to_s. You still need to find out why it is always nil, perhaps you intend to call @demographic.race_id?

OTHER TIPS

Based on your relationships,

class Demographic < ActiveRecord::Base
  has_one :race
end

class Race < ActiveRecord::Base
  belongs_to :demographic
end

your Race model should have an attribute demographic_id, not the way you have it now where Demographic has a race_id column.. Then, to reference the race that belongs to @demographic, you can just do @demographic.race

Edit:

After reading your comment below, it sounds like you want something where if you had a race (@race), you can get all of its demographic @race.demographics. You also want a demographic instance, @demographic, to belong to a race so that when you do @demographic.race, you get the race of that demographic.

If this is true, then you want to change your relationship to:

class Demographic < ActiveRecord::Base
  belongs_to :race
end

class Race < ActiveRecord::Base
  has_many :demographic
end

and in this case, it would be correct to have a race_id column in your Demographic model.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top