Search code examples
ruby-on-railspostgresqlrails-activerecord

PostgreSQL jsonb field in ActiveRecord belongs_to association


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'"

Solution

  • 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 [, ... ] ) ]