Rails多态类型和关联。如何更改对象类型/类?

时间:2017-02-18 07:17:19

标签: ruby-on-rails ruby-on-rails-4

我正试图改变现有对象的多态对象类型而没有任何成功。我认为它没有发生,因为模型与另一个模型有关联。 我使用的是Rails 4.1.7

我有一些这样的模型:

class User < ActiveRecord::Base
    TYPES = %w(Internal External)
    belongs_to :group
    validates :group, presence: true
end

class User::Internal < User
    belongs_to :group, :class_name => 'Group::Internal'
end

class User::External < User
    belongs_to :group, :class_name => 'Group::External'
end

class Group < ActiveRecord::Base
    TYPES = %w(Internal External)
    has_many :users
end

我已尝试使用以下代码将现有内部用户更改为外部:

extgroup = Group.find(5)
myuser = User.find(105)
myuser.becomes! User::External
myuser.type="User::External"
myuser.group = extgroup

在此之后我收到了错误消息:ActiveRecord :: AssociationTypeMismatch Group :: Internal expected,got Group :: External

如何在此示例中更改用户类型?

0 个答案:

没有答案