Skip to content
This repository was archived by the owner on Jun 17, 2020. It is now read-only.
This repository was archived by the owner on Jun 17, 2020. It is now read-only.

Using ActiveRecord in migrations guideline #222

@Bartuz

Description

@Bartuz

I'm migrating discussion here.

To wrap up what we have so far:
@Machiaweliczny:

Reopen AR model in migration and reuse it

class Entry < ActiveRecord::Base;end
def up
  Entry.where(feed_id: nil).destroy_all
  Entry.where(start_date: nil).destroy_all
  Entry.where(end_date: nil).destroy_al
end

@teamon :

Never, never, never use models inside migrations. Use only raw SQL!!

@hodak :

Hmm, why? He defined class Entry < ActiveRecord::Base. Isn't it less error-prone than raw SQL?

@teamon :

The question is - does this inner Entry class is completely new or just opens the Entry model. If it's the latter then this is still quite dangerous.

DELETE FROM entries WHERE feed_is IS NULL OR start_date IS NULL OR end_date IS NULL

Since AR does not care about correct field names for me raw SQL and hacked AR as error-prone at the same level

@jandudulski:

Uhm, to be honest, I don't see any difference between manually injected model and sql created by hand - on both cases it would explode if you pass invalid column (field) names.

me :

I see 3 solutions:
1.: GenericeModel

class DontAllowNullInEntries < ActiveRecord::Migration
  class GenericModel < ActiveRecord::Base
    self.table_name = 'entries
  end
  def up
      GenericModel.where(...
      ...
  end
def down; end
end

2.: Use Entry AR model but with reset_column_information (http://apidock.com/rails/ActiveRecord/ModelSchema/ClassMethods/reset_column_information)
3. : Use Andand. https://github.com/raganwald/andand

IMHO:

Personally I believe reset_column_information is the best solution as it is proposed by Rails Guides™

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions