Reputation: 261
I have two tables, Article
and Article_metadata
.
I added reference and foreign key between these two tables. But rails will some how takes article_id
(id column of Article table) as foreign key.
But i want another column in Article table (Article_uuid
) as my foreign key. How do i do it ?
This is how i'm doing it now. In create Article_metadata
migration file:
add_reference :article_metadata, :article, foreign_key: true
Upvotes: 0
Views: 2967
Reputation: 3255
In your ArticleMetaData class, add a custom foreign key to the belongs_to declaration. Here's an example:
class ArticleMetaData < ActiveRecord::Base
table_name "Article_metadata"
belongs_to :article, foreign_key: "article_uuid"
end
add_reference actually creates a new column and index, but it sounds like your columns already exist so you wouldn't need new ones.
To reference the meta data from the article, modify your article model to reference the same foreign_key field:
class Article < ActiveRecord::Base
# Tell ActiveRecord which column is the primary key (id by default)
self.primary_key = 'uuid'
# Tell the relationship which field on the meta_data table to use to match this table's primary key
has_one :meta_data, foreign_key: "article_uuid", class_name: "ArticleMetaData"
end
Upvotes: 3