Ruby Rails 通过迁移文件更新数据库中的元素

Ruby on Rails update element in database via Migrate file

我需要更新数据库中几个元组的名称属性。在本地,我可以通过 GUI -- pgAdmin 更新数据。

但我是 rails 的新手,不确定如何实际更新开发者数据库。

一位同事简短地建议编辑一个 db/migrate 文件来完成此操作。我可以用某种方法做到这一点吗?

或者通过命令行更好地完成类似的事情?

我正在使用 postgres。

class UpdateActionableItemName < ActiveRecord::Migration

  class InsightReportMenuItem < ActiveRecord::Base
    self.table_name = 'actionable_items'
    attr_accessible :name
  end

  def up
    #find all the rows to be updated
    prescriber_activity_request = InsightReportMenuItem.where(name: "Prescriber Activity With Patient")
    dispenser_activity_request = InsightReportMenuItem.where(name: "Dispenser Activity")
    patient_history_request = InsightReportMenuItem.where(name: "Patient Request Activity")
    #update row attributes
    prescriber_activity_request.update_attribute(name: "Prescriber Activity Request") if prescriber_activity_request
    dispenser_activity_request.update_attribute(name: "Dispenser Activity Request") if dispenser_activity_request
    patient_history_request.update_attribute(name: "Patient History Request") if patient_history_request
    #save updates
    prescriber_activity_request.save!
    dispenser_activity_request.save!
    patient_history_request.save!
  end

  def down
    #find all the rows to be updated
    prescriber_activity_request = InsightReportMenuItem.where(name: "Prescriber Activity Request")
    dispenser_activity_request = InsightReportMenuItem.where(name: "Dispenser Activity Request")
    patient_history_request = InsightReportMenuItem.where(name: "Patient History Request")
    #update row attributes
    prescriber_activity_request.update_attribute(name: "Prescriber Activity With Request") if prescriber_activity_request
    dispenser_activity_request.update_attribute(name: "Dispenser Activity") if dispenser_activity_request
    patient_history_request.update_attribute(name: "Patient Request Activity") if patient_history_request
    #save updates
    prescriber_activity_request.save!
    dispenser_activity_request.save!
    patient_history_request.save!
  end
end

是的,您可以通过 Rails 控制台执行此操作,但是,迁移文件是更好的方法,并且当他们提取最新代码时,对所有开发人员的机器产生相同的效果,他们将获得运行 迁移文件错误。有了这个,他们将对他们的机器进行相同的更改。

请注意,一旦推送到您的存储库,不要 编辑迁移文件。创建新的迁移文件并添加代码以根据需要操作您的数据库记录。

更新:

我不确定我是否理解你的评论,但是,如果你想知道将代码添加到迁移文件中以更新行的方法,它与我们在 rails 控制台上所做的相同。例如,如果您有 table users 并且您需要为 id 60 更新 name 列。如果您有模型 class:

user = User.find(60)
user.update_attribute(name: "New Name") if user

如果您没有模型 class User,您可以使用原始 SQL 直接更新行:

query = "UPDATE users set name = 'New Name' WHERE id = 60"
ActiveRecord::Base.connection.execute(sql)