Accessing a model from controller not working.

Hi could someone please put me right. I am not having any success at accessing my model from a controller.Please look at the code:

Model:

class Region < ActiveRecord::Base

  def self.get_region_code(region)     find_by_region("#{region}")   end

end

Controller code:

@region = Region.get_region_code(@region_name)

When I try to access the contents of @region

puts @region.region

It blows up with:

NoMethodError in Admin supplierController#update

You have a nil object when you didn't expect it! The error occurred while evaluating nil.region

Thankyou very much.

Paul Thompson.

Hi --

Hi could someone please put me right. I am not having any success at accessing my model from a controller.Please look at the code:

Model:

class Region < ActiveRecord::Base

def self.get_region_code(region)     find_by_region("#{region}") end

If region is a string, then you don't need to quote and interpolate it. That will just produce the same string again.

I'm not sure why you need to wrap find_by_region. Can't you just use that in the controller?

end

Controller code:

@region = Region.get_region_code(@region_name)

When I try to access the contents of @region

puts @region.region

It blows up with:

NoMethodError in Admin supplierController#update

You have a nil object when you didn't expect it! The error occurred while evaluating nil.region

That means that your call to Region.get_region_code returned nil. You'd need to do some inspecting to see what's in @region_name at the time of the call.

David

Hi David,

Thank you for your advice. It worked when I changed the code in the controller to:

@region = Region.find_by_region(@region_name)

rather than the previous code. But now I am confused, because I would have said that I am doing the identical thing. Where is my thinking wrong? As I have used the previous method before (with a different model and controller) and it worked just fine. The reason that I used the previous method was that I thought it was the correct way to do it.

Regards, Paul