[英]Rails belongs_to relationship with multiple possibilities
我試圖建立一種關系,其中模型, Information
,屬於User
或Client
。
我考慮過要放入Information.rb
belongs_to :user
belongs_to :client
並在User.rb
和Client.rb
has_one:信息
但這使得信息可以belong_to
User
和Client
。
有沒有一種方法可以使它只能屬於一個字段,也可以只將其中一個字段留空?
PS:如果需要,我將使用Rails 4.2,Ruby 2.2.1和Devise進行帳戶身份驗證。
謝謝!
這聽起來像一個不尋常的關聯,但非常適合多態關聯 。 在這種情況下,您將為此關聯聲明一個名稱
class Information < ActiveRecord::Base
belongs_to :informational, polymorphic: true #or something like it
class User < ActiveRecord::Base
has_many informations, as :informational
class Client < ActiveRecord::Base
has_many informations, as :informational
而且,您還需要在Information
informational_id, :integer
和informational_type, :string
添加兩列
Client
和User
需要一個稱為informational_id
的整數並對其進行索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.