Rails 3.2.11 MySql2 Gem
Hi, does anybody have an idea why my find method is returning an activerecord of the wrong type?
Here's the model:
class NameList < ActiveRecord::Base
attr_accessible :name, :selected, :type
self.table_name='name_lists'
end
Here's the console output:
>> k=NameList.find(28)
NameList Load (0.0ms) SELECT `name_lists`.* FROM `name_lists` WHERE `name_lists`.`id` = 28 LIMIT 1
#<Neighborhood id: 28, name: "Bayview">
>> k.class
Neighborhood(id: integer, city_id: integer, name: string, street_count: integer, relative_value: float, home_count: integer, min_lot_size: integer, created_at: datetime, updated_at: datetime)
Notice that I am calling NameList.find, but what I get back is Neighborhood object. Oddly, the sql seems right -- its querying the NameList table.
There's nothing particularly special about the Neighborhood object: Here's the model for that:
class Neighborhood < ActiveRecord::Base
belongs_to :city
has_many :streets
attr_accessible :name, :relative_value, :street_count
def self.make(name, relative_value, min_lot_size, street_count, home_count)
n=Neighborhood.new
n.name = name
end
end
When I try to save it though -- it uses the definition of schema of Neighborhood and tries to update the wrong table.
> k.name = "Foo"
"Foo"
>> k.save
(1.0ms) BEGIN
(0.0ms) UPDATE `neighborhoods` SET `name` = 'Foo', `updated_at` = '2013-03-14 17:40:46' WHERE `neighborhoods`.`id` = 28
(0.0ms) COMMIT
true
Any ideas?
You have stumbled upon Rails Single Table Inheritance (STI), which you immediately get if you add a 'type' column to your table. Essentially the object is instantiated from the class whose name matches the value of the type column in that record.
If you want to learn about STI, read on here, look for the Single Table Inheritance section. In your case, I bet you don't really want that behavior, so your solution is to rename the column to something like kind, category, or whatever makes sense to you
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With