Hi,
I’ve got a really simple model and controller which are producing an
error. The model is one line:
class NaturalPerson < ActiveRecord::Base
belongs_to :nationality, {:class_name => "Country"}
end
and the controller, specifically the create action, is equally simple:
class NaturalPeopleController < ApplicationController
def create
person = NaturalPerson.new(params[:natural_person])
if person.save
flash[:notice] = "Person was successfully created"
redirect_to :action => "list"
else
render_scaffold('new')
end
end
end
If I run the code like this I get this error:
ActiveRecord::AssociationTypeMismatch in Natural
peopleController#create
Country expected, got String
I have given ActiveRecord enough information to know it should
instantiate a Country and assign to “nationality”, no?
OK, so I need to do it myself in a constructor for the NaturalPerson
model:
def initialize(params)
@postal_address = params[:postal_address]
@fax_number = params[:fax_number]
@name = params[:name]
@phone_number = params[:phone_number]
@dob = Date.civil(params[“dob(1i)”].to_i, params[“dob(2i)”].to_i,
params[“dob(3i)”].to_i)
@visa =params[:visa]
@mobile_number = params[:mobile_number]
@email_address = params[:email_address]
@nationality = Country.find(params[:nationality].to_i)
end
Now I get this error:
NoMethodError in Natural peopleController#create
undefined method `updated?' for #<Country:0x412cb0a0
@attributes={"name"=>"TONGA", "id"=>"220"}>
A search of the web and usenet suggests that the “definitive” reason for
this error is described in this post:
http://lists.rubyonrails.org/pipermail/rails/2006-March/026246.html
"my problem was caused by a badly chosen name of a variable
in the validates method of my interface model. Originally
I called it @device, after renaming it the error was gone."
Unfortuately the post doesn’t say what it was about the variable name
what was bad. This thread provides another useful tidbit of information:
"Looking back at the reason, it would never get into the block
that I mentioned in my original post if the :belongs_to object
is null and if i have a different variable name, that would be
the case and the association is only saved due to the link
from the Doctor's side."
OK. In my case the belongs_to object is nil because it hasn’t been
assigned a value yet.
The name of my foreign key was originally “nationality” but, without
really knowing what was causing the problem, I thought there might be
some conflict with the instance variable so I changed the field to
“country_id”. Hence this code in the model:
belongs_to :nationality, {:class_name => "Country"}
which implies a foreign key of “country_id”.
So I’m at a point where I don’t think the previous examples of this
error apply to me. If anyone has any suggestions I would be extremely
grateful!
Regards,
Michael