在你ArticleMetaData類,添加自定義外鍵belongs_to的聲明。這裏有一個例子:
class ArticleMetaData < ActiveRecord::Base
table_name "Article_metadata"
belongs_to :article, foreign_key: "article_uuid"
end
add_reference實際上創建了一個新的列和索引,但它聽起來像是已經存在您的欄,你就不需要新的。
從文章中引用的元數據,修改你的文章的模型引用相同的foreign_key領域:
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
Hw的我可以檢索文章的元數據爲特定的文章?我可以做Article.Article_metadata嗎? – Lollypop
而新創建的外鍵列默認爲整數數據類型,我如何設置數據類型爲字符串或varchar? – Lollypop
我做了一個編輯,向您展示如何從文章中查找元數據。不知道你的模型名稱實際上是什麼,你可能需要調整一下,但其餘的都很好。 –