简体   繁体   中英

Migrating records from one table column to another table column. (rails)

I'm working on a rails project in which I need to take some records from one table to another table. Its kinda straight forward.....but i've been having problems and I hope someone could help me out with it.

Basically I've got a record column named research_consent that is in a table named state , that I need to move to a new table named configuration .

The research_consent is a string in the state table, and remains a string in the configuration table.

Below I have the migration that I attempted. I attempted to go through where the states where they had research_consent_text and then move them into the configurations table. (I got a feeling that I'm over-thinking this)

def change
  State.where.not(research_consent_text: ["", nil]).each do |state|
    config = state.research_consent_text
    next if state.research_consent_text.present?
    configuration.update_attributes(research_consent_text: state.research_consent_text)
    config.save
  end
end

If anybody could take a quick look at this and either tell me a far better way to move this, or muddle through my pitiful attempt and let me know if there is a better way, I would greatly appreciate this!

I would do something like this

def change
  State.where.not(research_consent_text: ["", nil]).each do |state|
    configuration.find_or_create_by(research_consent_text: state.research_consent_text) do |configuration|
      configuration.anything_else
    end
  end
end

you can see more on find_or_create_by

I hope that this helps. Happy hacking

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM