2015-07-20 62 views
-1

我想使用activerecord进行一个sql查询,我很难从多个连接的表中指定一个特定的列。活动记录如何在连接后指定一列?

例如在SQL

select go.id, sequence.name, sequence.id from sequence join (goterms,...) on ... 

这是不漂亮,但SQL我的观点是,我能够指定.ID我想回到

在ActiveRecord的

我这样做:

results = Sequence.joins(:Foreigndb,:Goterm,:Taxa) 
.select(:header,:taxaclass, :genus, :interpro_desc,:description,:dbname,:read_depth, :name) 
.distinct 

我希望能够从中获取ID:Goterm但:类群和:Foreigndb还使用id作为数据库中的一列,因此我得到我认为从这个问题的时候干我不提供信息的错误 请执行下列操作。

results = Sequence.joins(:Foreigndb,:Goterm,:Taxa) 
.select(:header,:taxaclass, :genus, :interpro_desc,:description,:dbname,:read_depth, :name,:id) 
.distinct 

什么是正确的方式来指定我想Goterm.id?

编辑 - 以下是错误:
的ActiveRecord :: StatementInvalid:Mysql2 ::错误:未知列 'Goterm.id' 在 '字段列表'

当我运行: 结果= Sequence.joins( :foreigndb,:Goterm,:taxa).select(:header,:taxaclass,:genus,:interpro_desc,:description,:dbname,:read_depth,:name,'Goterm.id')。limit(5).offset( 0).dresults = Sequence.joins(:Foreigndb,:Goterm,:Taxa).select(:header,:taxaclass,:genus,:interpro_desc,:description,:dbname,:read_depth,:name,'Goterm.id' ).limit(5).offset(0).distinct

回答

0
results = Sequence.joins(:Foreigndb,:Goterm,:Taxa).select(:header,:taxaclass, :genus, :interpro_desc,:description,:dbname,:read_depth, :name, 'sequences.id') 
.distinct 
+0

birci我想这一点,但仍然返回了一个错误:结果= Sequence.joins(:Foreigndb,:Goterm,:分类群)。选择(:头, :taxaclass,:genus,:interpro_desc,:description,:dbname,:read_depth,:name,'Goterm.id')。limit(5).offset(0).distinct。再次出现模棱两可的错误 – Zach

+0

您可以发布错误吗? –

0

事实证明,伊兰的答案是正确的,但要确保一切都是小写。我在使用'Goterm.id'进行选择时,它需要'goterm.id'

如果有其他人遇到这个问题,我还遇到困难,从返回的查询对象中抓取goterm.id数据。每次我在该返回集上调用object.id时,它都会给我一些与我期望的不同的东西。我认为我期待的属性被别的东西遮蔽了。为了获取数据,我需要我做了以下内容:

results = Sequence.joins(:Foreigndb,:Goterm,:Taxa).select(:header,:taxaclass, :genus,:interpro_desc,:description,:dbname,:read_depth, :name).distinct 
firstRes = results[0] 
firstRes.attributes['id'] 
相关问题