简体   繁体   English

使用联接选择属性并在Rails中选择

[英]Selecting attributes using joins and select in rails

I have a TopicRelation class which builds a relationship between two topics, using source_topic_id and target_topic_id . 我有一个TopicRelation类,它使用source_topic_idtarget_topic_id在两个主题之间建立关系。 Here is the model: 这是模型:

class TopicRelation < ActiveRecord::Base
  belongs_to :source_topic, class_name: 'Topic'
  belongs_to :target_topic, class_name: 'Topic'
end

I am trying to pull just the name of the source topic: 我试图仅提取源主题的名称:

TopicRelation.joins(:source_topic, :target_topic)
  .where('source_topic_id=?', topic.id)
  .select('source_topics.name')

However, this gives me the following error: 但是,这给了我以下错误:

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

Is it possible to select the name for both source_topic and target_topic using this approach? 是否可以使用这种方法选择source_topictarget_topic的名称?

The select use the name of the db table, which is likely topics in your case : select使用数据库表的名称,在您的情况下,这可能是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')

Also this will return a list of TopicRelation ; 同样,这将返回TopicRelation的列表; If you want only the name of the topics, use the method pluck instead of select 如果只需要主题名称,请使用pluck方法而不是select

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM