简体   繁体   English

在Rails迁移中从模型调用方法?

[英]Calling a method from a model in a rails migration?

Super new to rails, but is it possible to call methods from a model in a migration? 对Rails来说是超级新手,但是可以在迁移中从模型中调用方法吗?

Lets say I have a model that looks like: 可以说我有一个看起来像这样的模型:

class Orders < ApplicationRecord

   def order_size
      Order.where(item_id: 1).count
   end


   def order_level (order_size)
     if order_size =< 2
       Order.update_all(customer_level: "Bronze")
     elsif order_size >= 3 && order_size < 6
       Order.update_all(customer_level: "Silver")
     elsif order_size >= 6
       Order.update_all(customer_level: "Gold")
     end
   end

end

Could I run a migration that will only update certain size orders, such as: 我可以运行仅更新某些尺寸订单的迁移,例如:

class SomeMigration < ActiveRecord::Migration
    def change
       if order_size == 10
         (call/do order_level)
       end
    end
 end

Just for context, I've implemented a separate functionality that will automatically update an order's customer_level when a new order is created with order_level , but I need to go back and update all of the orders that already exist. 仅出于上下文考虑,我实现了一个单独的功能,当使用order_level创建新订单时,该功能将自动更新订单的customer_level ,但是我需要返回并更新所有已存在的订单。 I only really care about orders that are 10+ in this case. 在这种情况下,我只真正关心的是10个以上的订单。

Hope this makes sense and isn't completely ridiculous! 希望这是有道理的,并且不是完全荒谬的!

Thanks 谢谢

is it possible to call methods from a model in a migration? 迁移中是否可以从模型中调用方法?

Yes. 是。 As illustrated in the docs, section 8 Migrations and Seed Data , you can call model methods in a migration. 文档第8节“迁移和种子数据”所示 ,您可以在迁移中调用模型方法。 Here is the sample code from the docs: 这是来自文档的示例代码:

class AddInitialProducts < ActiveRecord::Migration[5.0]
  def up
    5.times do |i|
      Product.create(name: "Product ##{i}", description: "A product.")
    end
  end

  def down
    Product.delete_all
  end
end

Whether it is a good idea or not is a separate question. 一个好主意是否是一个单独的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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