ActiveRecord Issues - Uninitialized Contant

Hi,

Just having a play around with RoR for a few little automation tasks and it’s doing my nut in right now. I’ve got two models:

Item:


class Item < ActiveRecord::Base
  belongs_to :something
end

Something:


class SomeThing < ActiveRecord::Base
    has_many :items
end

The table for items has: something_id column in it.

Yet when I try:


<%=h item.something.value %>

I get:


uninitialized constant Item::Something

and it’s doing my head in right now as to why it isn’t working.

It’s bound to be something simple that I’m just not seeing, having come from many years with PHP.

Cheers,

Is that exactly the code you have? because you’d need to actually specify the name of the correct model (e.g. in the case you’ve provided you’d need to say belongs_to :rate and not belongs_to :something).

If the name of the class is different from the name of the relation you want to use, you need to specify :class_name in your belongs_to declaration.

Hi,

Sorry, that should have been class Something not class Rate, that swhat I get for looking at two different tinges when I’m posting.

Thanks,

So, do you mean you’ve got it working now, or do you just mean that your initial query should have had that class name?

Hi,

No, it was a typo in my original post. The models were a little more complex than as posted, but I’ve stripped them down to what you see now in my original (edited) post and it’s having non of it.

Thanks,

Cool,

Now I’m seeing one more potential issue: you have class SomeThing camel-cased. If that’s indeed the case, you should be using item.some_thing and not item.something … Rails automatically inflects your camel-cased names for use in file names and database tables, and that’s also reflected in the accessor methods generated by belongs_to or has_many.

Hi,

I did actually try that before, so item looks like this:


class Item < ActiveRecord::Base
  belongs_to :some_thing
end

Now that just gives me a different error:


undefined method `value' for nil:NilClass

When doing:


&lt;%=h item.some_thing.value %&gt;

value does exist, as you can see from the schema:


  create_table "some_things", :force =&gt; true do |t|
    t.integer  "value"
    t.string   "name"
    t.string   "description"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

Thanks,

Cool. Believe it or not, that’s progress :slight_smile:

At this point the method some_thing of your item isn’t throwing an error like it was before, so your association is set up correctly. However, you’re getting nil when retrieving the some_thing associated with that particular item, which would imply that it doesn’t have one. Try creating a new item and make sure there’s a some_thing associated with it. If you’re looping over a list of items, and only some of them will have some_things, you’ll need to check to see if they’re there before trying to get their properties:


if item.some_thing
  item.some_thing.value
end