简体   繁体   English

有多种可能的Rails归属关系

[英]Rails belongs_to relationship with multiple possibilities

I'm trying to make a relationship where a model, Information , belongs_to either a User or a Client . 我试图建立一种关系,其中模型, Information ,属于UserClient

I thought about putting in my Information.rb 我考虑过要放入Information.rb

belongs_to :user
belongs_to :client

and in User.rb and Client.rb 并在User.rbClient.rb

has_one :information has_one:信息

But that makes it so that an information could belong_to both a User and a Client . 但这使得信息可以belong_to UserClient

Is there a way to make it so that it can only belong to either or without just leaving one of the fields blank? 有没有一种方法可以使它只能属于一个字段,也可以只将其中一个字段留空?

PS If it is needed I'm using Rails 4.2, Ruby 2.2.1, and Devise for my account authentication. PS:如果需要,我将使用Rails 4.2,Ruby 2.2.1和Devise进行帐户身份验证。

Thanks! 谢谢!

This sounds like an unusual association but it's a good fit for Polymorphic Association . 这听起来像一个不寻常的关联,但非常适合多态关联 In this case, you would declare a name for this association 在这种情况下,您将为此关联声明一个名称

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

And you would also need to add two columns to Information informational_id, :integer and informational_type, :string 而且,您还需要在Information informational_id, :integerinformational_type, :string添加两列

and Client and User need a integer called informational_id that is indexed. ClientUser需要一个称为informational_id的整数并对其进行索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM