Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 使用Select强制ActiveRecord中的数据类型_Ruby On Rails_Ruby On Rails 3_Activerecord - Fatal编程技术网

Ruby on rails 使用Select强制ActiveRecord中的数据类型

Ruby on rails 使用Select强制ActiveRecord中的数据类型,ruby-on-rails,ruby-on-rails-3,activerecord,Ruby On Rails,Ruby On Rails 3,Activerecord,我正在运行一个包含联接和冲突列名的查询。即: results = TableA.joins(:table_b).select('table_a.id as table_a_id', 'table_b.id as table_b_id') 在我的结果中,table_a_id和table_b_id都是字符串。我怎样才能使它们成为整数 我觉得可能有一种方法可以让它返回results[0]['table_a']['id']和results[0]['table_b']['id'],两者都有正确的数据类型

我正在运行一个包含联接和冲突列名的查询。即:

results = TableA.joins(:table_b).select('table_a.id as table_a_id', 'table_b.id as table_b_id')
在我的结果中,table_a_id和table_b_id都是字符串。我怎样才能使它们成为整数

我觉得可能有一种方法可以让它返回
results[0]['table_a']['id']
results[0]['table_b']['id']
,两者都有正确的数据类型,但我不知道怎么做

我主要关心的是使其能够在不运行第二个查询的情况下访问这两个列


谢谢

这对我很管用。我这样做:

comments = Comment.joins(:project).select('comments.id as table_a_id, projects.id as table_b_id')
comments.first.table_a_id
我可以这样做:

comments = Comment.joins(:project).select('comments.id as table_a_id, projects.id as table_b_id')
comments.first.table_a_id

要将列转换为整数,可以使用sql函数。要转换为整数,可以使用sql或ruby函数。

因为Dougui的答案几乎涵盖了访问这两列,所以我只讨论字符串到整数的转换。 您有两种选择,用SQL或Ruby进行转换

在Ruby中,可以调用字符串上的
。将其转换为整数,从而:

> foo = '156'
=> '156'
> foo.to_i
=> 156
在SQL中,您使用
CAST
函数,因此:

SELECT CAST('156' AS INTEGER);

 int4 
------
  156
(1 row)

虽然有点晚了,但也许会有用

我遇到了同样的问题,我解决了这样的问题:

从@Dougui的答案开始,您可以强制
表\u b\u id
类型定义:

class TableA
  def [](name)
    if name.to_sym == :table_b_id
      super.to_i
    else
      super
    end
  end

  def method_missing(name, *args)
    if name.to_sym == :table_b_id && args.empty? && !block_given?
      super.to_i
    else
      super
    end
  end
end

所以我的问题是,当我
.select()
指定列时,即使是整数类型的列也会作为字符串返回Rails。这是正常的行为吗?嗯,是的,似乎确实发生过。以前从未注意过。我猜你被困在做你的字符串到整数转换后的事实。