ActiveRecord, single inheritance (STI)

Hi, when using STI, Do I have to set type column’s value explicity or
is it set by Rails?

Eduardo Yáñez Parareda wrote:

Hi, when using STI, Do I have to set type column’s value explicity or
is it set by Rails?

Rails handles it all for you.

Chris

On 24 Aug 2006, at 11:22, Eduardo Yáñez Parareda wrote:

Hi, when using STI, Do I have to set type column’s value explicity or
is it set by Rails?

It’s set by rails, assuming you have a type column


Alastair M.
Standards compliant web development with Ruby On Rails, PHP and ASP
www.kozmo.co.uk
07738 399038

It’s set by rails, assuming you have a type column

Well, I asked it because I have this migration:

class CreateFormations < ActiveRecord::Migration
def self.up
create_table :formations do |t|
# Esta columna es para soportar herencia entre Formation y
TeamFormation
t.column :type, :string
t.column :name, :string, :limit => 16, :null => false

  # Atributos para TeamFormations
  t.column :match_id, :integer
  t.column :team_id, :integer
end

# Creamos por defecto el tipo de alineación 4-4-2
formation = Formation.create(:name => :'4-4-2')    <---- HERE I

CREATE AN OBJECT AND
formation.save!
SAVE IT
end

def self.down
drop_table :formations
end
end

Within there I save a new Formation but after that type column is null.

On 8/24/06, Eduardo Yáñez Parareda [email protected] wrote:

TeamFormation
CREATE AN OBJECT AND
formation.save!
SAVE IT
end

def self.down
drop_table :formations
end
end

Okay so Formation has your type column then. I don’t believe that you want
to be creating objects based on it directly. Try this

class Specialformation < Formation
end
class Differentformation < Formation
end

sf= Specialformation.create(:name => ‘4-4-2’)
df = Differentformation.create(:name => ‘3-5-2’)
If you peek into your formations table, you should see two new records,
with
correct type fields.

HTH,
Howard

On 24 Aug 2006, at 12:04, Eduardo Yáñez Parareda wrote:

  t.column :type, :string
formation.save!
SAVE IT

end

def self.down
drop_table :formations
end
end

Within there I save a new Formation but after that type column is
null.

I think that is because it is assumed unless you’re inheriting the
model Formation, in your example, you’re creating a new Formation.
If you were to create a TeamFormation model -

class TeamFormation < Formation

and then

TeamFormation.create :name => ‘4-4-2’

in your Formation table, it will insert the type TeamFormation.
Formation isn’t inheriting anything.


Alastair M.
Standards compliant web development with Ruby On Rails, PHP and ASP
www.kozmo.co.uk
07738 399038