[ruby-it] le foreign keys.
Mauro
mrsanna1 a gmail.com
Mar 16 Dic 2008 23:04:13 CET
2008/12/16 Paolo Montrasio <paolo a paolomontrasio.com>
> A quanto ho capito, ma potrei sbagliarmi, il metodo references crea
> nella tabella i campi con i nomi giusti per poi essere usati
> dall'accoppiata belongs_to e has_one/many, perņ non crea la foreign key
> nello schema del db.
>
> Mauro wrote:
> > 2008/12/16 Salvatore <safeforge a gmail.com>
> >
> >> Io ho risolto con un plugin molto carino (foreign_key_migrations) per�
> > sono nuovo di questo mondo
> >> magari c'� un metodo migliore, la parola agli esperti :)
> >
> >
> > allora esperti fatevi sentire dai.....
>
> Non conoscevo quel plugin ma da quel che ho visto nella sua
> documentazione pare risolvere il problema molto bene. Finora, proprio
> con PostgreSQL, includevo questo modulo nelle migration perņ adesso
> forse cambierņ abitudini.
>
> -------------
> module MigrationHelpers
> def foreign_key(from_table, from_column, to_table)
> constraint_name = "fk_#{from_table}_#{from_column}"
>
> execute %{alter table #{from_table}
> add constraint #{constraint_name}
> foreign key (#{from_column})
> references #{to_table}(id)}
> end
>
> def remove_foreign_key(from_table, from_column)
> constraint_name = "fk_#{from_table}_#{from_column}"
>
> execute %{alter table #{from_table}
> drop constraint #{constraint_name}}
> end
> end
> -------------
>
Nel manuale Agile development with rails, nell'applicazione di esempio, per
creare le foreign keys fa una cosa del genere:
class CreateLineItems < ActiveRecord::Migration
def self.up
create_table :line_items do |t|
t.integer :product_id, :null => false, :options => "CONSTRAINT
fk_line_item_products REFERENCES products(id)"
t.integer :order_id, :null => false, :options => "CONSTRAINT
fk_line_item_orders REFERENCES orders(id)"
t.integer :quantity, :null => false
t.decimal :total_price, :null => false, :precision => 8, :scale =>
2
t.timestamps
end
end
def self.down
drop_table :line_items
end
end
More information about the Ml
mailing list