Foreign keys in Rails 3

后端 未结 3 1931
离开以前
离开以前 2021-02-08 08:17

I understand that according to Rails philosophy, data integrity checks should be done at the application level as opposed to the database level. Like many other developers, I en

3条回答
  •  半阙折子戏
    2021-02-08 09:04

    It is for this reason that I (and the people who wrote Enterprise Rails - http://oreilly.com/catalog/9780596515201) recommend that you write your entire up and down migrations in SQL.

    The advantages are:

    • The ability to add foreign keys on table creation - without a separate alter table
    • It allows you to use database specific field types - like tsvectors
    • It allows you to add different types of indexes - like Gin or Gist
    • It allows you to write functions and/or triggers
    • You wont have to remember what DSL type relates to what SQL field type - e.g. :number

    There are disadvantages:

    • It's not database agnostic (who cares and how often will you change your database?)
    • It's not Ruby (but every good Rails developer should know SQL, right?)

    But, overall I reckon the advantages outweigh the disadvantages.

    Quick example:

      def self.up
        execute <

提交回复
热议问题