簡體   English   中英

有多種可能的Rails歸屬關系

[英]Rails belongs_to relationship with multiple possibilities

我試圖建立一種關系,其中模型, Information ,屬於UserClient

我考慮過要放入Information.rb

belongs_to :user
belongs_to :client

並在User.rbClient.rb

has_one:信息

但這使得信息可以belong_to UserClient

有沒有一種方法可以使它只能屬於一個字段,也可以只將其中一個字段留空?

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, :integerinformational_type, :string添加兩列

ClientUser需要一個稱為informational_id的整數並對其進行索引。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM