我正在修復過去設置'種類'的多態關聯。這裏是細節。修復多態關聯
User.rb has fields:
user_type_id
user_type
我需要User
屬於Company
或Employee
。
我遇到的問題是因爲User.rb字段未使用Rails約定命名(類似usable_type
和usable_id
)。我如何根據我所擁有的領域建立協會?
我正在修復過去設置'種類'的多態關聯。這裏是細節。修復多態關聯
User.rb has fields:
user_type_id
user_type
我需要User
屬於Company
或Employee
。
我遇到的問題是因爲User.rb字段未使用Rails約定命名(類似usable_type
和usable_id
)。我如何根據我所擁有的領域建立協會?
有一個無證:foreign_type
選項上belongs_to
:
class User < ActiveRecord::Base
belongs_to :user_type, :polymorphic => true, :foreign_type => 'user_type'
end
最容易改變字段的名稱以適應Rails約定:由於多態關聯還沒有正確設置,並且這些字段不應該用於其他任何事情,所以你應該沒有問題。
基本上你需要選擇一個名字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
這也將使更多維護的代碼以後。
我不能得到相反的協會合作 - 你怎麼辦相當於'has_one'? – sscirrus