在你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
我做了一个编辑,向您展示如何从文章中查找元数据。不知道你的模型名称实际上是什么,你可能需要调整一下,但其余的都很好。 –