Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.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 有没有办法使用Activerecord连接两个字段?不使用虚拟属性_Ruby On Rails_Ruby On Rails 4 - Fatal编程技术网

Ruby on rails 有没有办法使用Activerecord连接两个字段?不使用虚拟属性

Ruby on rails 有没有办法使用Activerecord连接两个字段?不使用虚拟属性,ruby-on-rails,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 4,我想把两个字段连接在一起,最好中间有一个空格。我知道这可以在模型级别完成,但我无法预测将混合哪些字段和表,因此我无法为此创建虚拟属性 下面是我试图做的一个过于简单的例子 表: # Product (id: integer, name: string, variety: string) # Location (id: integer, city: string) 这将给我一个位置关系,以及产品种类: p=Product.joins(:location).group(:location_id, :

我想把两个字段连接在一起,最好中间有一个空格。我知道这可以在模型级别完成,但我无法预测将混合哪些字段和表,因此我无法为此创建虚拟属性

下面是我试图做的一个过于简单的例子

表:

# Product (id: integer, name: string, variety: string)
# Location (id: integer, city: string)
这将给我一个位置关系,以及产品种类:

p=Product.joins(:location).group(:location_id, :variety).pluck(:city, :variety)
现在我需要将位置名称和品种名称连接在一起;这将是
city
来自位置和
variation
来自产品


这只是一个例子,但还有更多我无法预测的组合。我宁愿避免为此创建虚拟属性,因为为每个可能的组合添加一个属性是非常复杂的,而使用受影响的模型创建自己的函数对于这么简单的事情来说有点太多了。

为什么不能简单地在采集后加入结果?像这样:

p = Product.joins(:location).group(:location_id, :variety).
    pluck(:city, :variety).map{|e| e.join(' ')}

我知道这是一个老问题,但它是在谷歌搜索中出现的,我找到了一个更好的答案

@philip hallstrom的答案是可行的,但它将执行内存中的连接。在数据库级别执行连接会更有效,如下所示:

Product
  .joins(:location)
  .group(:location_id, :variety)
  .pluck("CONCAT_WS(' ', locations.city, products.variety)")

你能告诉我们更多关于你的用例吗?撇开实现不谈,您将如何使用它?结果值将以表格的形式发送到某种“报告”页面,其中的值将位于其中一个单元格中。我知道在模型级别进行安排会更好,但由于表的复杂性,我并不特别喜欢执行这项任务。因为使用Ruby执行这项任务,而不是直接使用DBMS,效率非常低。