我有一个TopicRelation类,它使用source_topic_id
和target_topic_id
在两个主题之间建立关系。这是模型:
class TopicRelation < ActiveRecord::Base
belongs_to :source_topic, class_name: 'Topic'
belongs_to :target_topic, class_name: 'Topic'
end
我试图仅提取源主题的名称:
TopicRelation.joins(:source_topic, :target_topic)
.where('source_topic_id=?', topic.id)
.select('source_topics.name')
然而,这给了我以下错误:
TopicRelation Load (113.7ms) SELECT source_topics.name FROM `topic_relations` INNER JOIN `topics` ON `topics`.`id` = `topic_relations`.`source_topic_id` INNER JOIN `topics` `target_topics_topic_relations` ON `target_topics_topic_relations`.`id` = `topic_relations`.`target_topic_id` WHERE (source_topic_id=1) LIMIT 10
Mysql2::Error: Unknown column 'source_topics.name' in 'field list': SELECT source_topics.name FROM `topic_relations` INNER JOIN `topics` ON `topics`.`id` = `topic_relations`.`source_topic_id` INNER JOIN `topics` `target_topics_topic_relations` ON `target_topics_topic_relations`.`id` = `topic_relations`.`target_topic_id` WHERE (source_topic_id=1) LIMIT 10
ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'source_topics.name' in 'field list': SELECT source_topics.name FROM `topic_relations` INNER JOIN `topics` ON `topics`.`id` = `topic_relations`.`source_topic_id` INNER JOIN `topics` `target_topics_topic_relations` ON `target_topics_topic_relations`.`id` = `topic_relations`.`target_topic_id` WHERE (source_topic_id=1) LIMIT 10
是否可以使用此方法为source_topic
和target_topic
选择名称?
答案 0 :(得分:0)
select
使用db表的名称,在您的情况下可能是topics
:
TopicRelation
.joins('INNER JOIN topics target_topics ON topic_relations.target_topic_id = target_topics.id')
.joins('INNER JOIN topics source_topics ON topic_relations.source_topic_id = source_topics.id')
.where(source_topic: topic)
.select('source_topics.name')
此外,这将返回TopicRelation
的列表;如果您只想要主题的名称,请使用方法pluck
而不是select