【问题标题】:Rails STI change typeRails STI 更改类型
【发布时间】:2012-05-30 23:44:18
【问题描述】:

我目前正在从事一个项目,我正在使用 STI 模型并希望将一个记录转换为另一种类型而不创建新记录。有些观察者会在创建新模型时触发,但是我不希望这些观察者触发并希望保持相同的 ID。有没有一种简单的方法可以通过 ORM 将记录从一个模型转换为另一个模型?而不使用 SQL?

干杯

【问题讨论】:

标签: ruby-on-rails polymorphic-associations sti


【解决方案1】:

#becomes可以为所欲为:

class Foo < ActiveRecord::Base
end

class Bar < Foo
end

class Baz < Foo
end

baz = Baz.create({})
bar = baz.becomes(Bar)

此时,foos 表中仍然有 baz 记录。您必须确保保存 bar 不会导致问题。

【讨论】:

    【解决方案2】:

    becomes! 对我不起作用,详见https://stackoverflow.com/a/26091638/1935918。相反,我建议使用update_column

      def update
        @company = Company.find(params[:id])
        # This separate step is required to change Single Table Inheritance types
        new_type = params[:company][:type]
        if new_type != @company.type && Company::COMPANY_TYPES.include?(new_type)
          @company.update_column :type, new_type
        end
    
        @company.update(company_params)
        respond_with(@company)
      end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多