如何通过从两个表中查找非主键列来连接活动记录中的两个表?



我有三个表,它们具有以下结构:

CREATE TABLE `crawled_data` (
`id` int NOT NULL,
`url` longtext,
***OMMITTED***
PRIMARY KEY (`id`)
);
CREATE TABLE `ingredient_frequency` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`url_id` int DEFAULT NULL,
`url` text,
***OMMITTED***
PRIMARY KEY (`id`)
)
CREATE TABLE `url_metadata` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`url` longtext,
***OMMITTED*** 
PRIMARY KEY (`id`)
);

我定义了以下活动记录结构:

class Crawled_Data < ActiveRecord::Base
self.table_name = "crawled_data"
has_many :url_metadatas
end
class Ingredient_Frequency < ActiveRecord::Base
self.table_name = "ingredient_frequency"
belongs_to :url_metadata
end
class Url_Metadata < ActiveRecord::Base
self.table_name = "url_metadata"
has_many :ingredient_frequencies
belongs_to :crawled_data
end

我应该如何继续加入crawled_data与url_metadata通过匹配url列(这不是主键在两个表)?

我看了下面的线程,但没有运气,因为答案并没有真正提到如何引用当前表的列(而只是谈论引用foreign_key)

如何在rails中连接没有主键的表?
class Crawled_Data < ActiveRecord::Base
self.table_name = "crawled_data"
has_many :url_metadatas, primary_key: 'url', foreign_key: 'url'
end
class Ingredient_Frequency < ActiveRecord::Base
self.table_name = "ingredient_frequency"
belongs_to :url_metadata, primary_key: 'url', foreign_key: 'url'
end
class Url_Metadata < ActiveRecord::Base
self.table_name = "url_metadata"
has_many :ingredient_frequencies, primary_key: 'url', foreign_key: 'url'
belongs_to :crawled_data, primary_key: 'url', foreign_key: 'url'
end

,然后:Crawled_Data.joins(:url_metadatas)

相关内容

  • 没有找到相关文章

最新更新