修复多态关联

时间:2011-08-21 22:30:22

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

我正在修复过去设置的“类型”多态关联。以下是详细信息。

User.rb has fields:
user_type_id
user_type

我需要User属于CompanyEmployee

我遇到的问题是因为User.rb字段没有使用Rails约定命名(类似usable_typeusable_id)。如何根据我的字段设置关联?

2 个答案:

答案 0 :(得分:2)

:foreign_type上有一个未记录的belongs_to选项:

class User < ActiveRecord::Base
  belongs_to :user_type, :polymorphic => true, :foreign_type => 'user_type'
end

答案 1 :(得分:0)

最容易更改字段的名称以适应Rails约定:由于多态关联尚未正确设置,并且这些字段不应用于其他任何内容,因此您不应该遇到问题。 / p>

基本上,您需要选择一个名称xyz以适合以下

class User < ActiveRecord::Base
    belongs_to :xyz, :polymorphic => true
end

class Employee < ActiveRecord::Base
    has_many :users, :as => :xyz
end

class Company < ActiveRecord::Base
    has_many :users, :as => :xyz
end

您的用户模型包含字段

User
xyz_id    :integer
xyz_type    :string

这也将在以后制作更易于维护的代码。

相关问题