質問

So, I've been using this piece of code inside my migrations in rails:

    add_column :target_table, :FK, :integer

    execute <<-SQL
      ALTER TABLE target_table
      ADD CONSTRAINT constraint FOREIGN KEY (FK)
      REFERENCES some_table (id)
      ON UPDATE CASCADE ON DELETE RESTRICT
    SQL

And as any good programmer, I would like to keep things as short and fast as possible.

I'm new to this language and would like to know if the code below is equivalent to my SQL (in all aspects).

    add_column :target_table, :FK, :integer, null: false
    add_index  :targe_table,  :FK

PLUS : If those codes were inside an up method, how should mine down method look like?

-- EDIT --

I've done some research and read about a third way of doing this:

    add_column :target_table, :FK, :integer, null: false, references: some_table

Are those all equivalent? Will the rails convention add the proper constraint to the index? I would really appreciate if some one could tell me the differences.

役に立ちましたか?

解決

the problem of having something like

execute <<-SQL
      ALTER TABLE target_table
      ADD CONSTRAINT constraint FOREIGN KEY (FK)
      REFERENCES some_table (id)
      ON UPDATE CASCADE ON DELETE RESTRICT
    SQL

on your migration file is that you are now stuck with SQL or the particular flavor of SQL that you are currently using. like you say the proper way of doing it is

add_index  :targe_table,  :FK

that ways the rails magic would know what flavor of SQL you where using and do the right thing

to do a down you would do

remove_index :targe_table, :FK

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top