问题
Can I use a jsonb field as a foreign_key in a belongs_to association? Something along the lines of:
belongs_to :product, class_name: "Product", foreign_key: "data ->'product_id'"
回答1:
References can be defined only between columns (or groups of columns), as it is stated in the documentation:
FOREIGN KEY ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ]
回答2:
you can use activerecord-json-associations to use PostgreSQL JSONB fields to store association information of your models
来源:https://stackoverflow.com/questions/32889252/postgresql-jsonb-field-in-activerecord-belongs-to-association