其中返回列名和值

时间:2013-02-03 12:48:27

标签: ruby-on-rails rails-activerecord

这是我的代码:

<%= DimensionVersion.where(:dimension_id => 1).select("name") %>

我希望获得维度版本名称列表,其中:dimension_id =&gt; 1.数据库中有四个。

相反,我得到了这个:

#<ActiveRecord::Relation:0x3d351c8>

编辑:

我想出了如何用这个回复我想要的东西:

<%= DimensionVersion.select("name").where(:dimension_id => 1).all %>

返回:

[#<DimensionVersion name: "Default">, #<DimensionVersion name: "Test1">, #<DimensionVersion name: "Test2">, #<DimensionVersion name: "Test3">]

但是,我不希望它与#<DimensionVersion Name: ... >一起返回。我尝试从前导标记中删除=,但之后没有返回任何内容。

3 个答案:

答案 0 :(得分:2)

DimensionVersion.where(:dimension_id => 1).select("name")

我认为你需要采用这种方法。

将以上内容改写为:

DimensionVersion.where(:dimension_id => 1).pluck(:name)

同样,即使像collect这样的更高级别的构造也可以用作:

DimensionVersion.where(:dimension_id => 1).collect(&:name)

希望这有帮助。

答案 1 :(得分:1)

AR返回Relation,以便您可以链接条件等。如果您想要实际结果,请在其上调用#all#first#each,...:

DimensionVersion.where(:dimension_id => 1).select("name").all
  

使用rails查询是一件非常痛苦的事情我即将放弃整个框架并回到php。

您可能需要阅读指南:Active Record Query Interface

答案 2 :(得分:0)

我能够通过使用像这样的collect方法来删除列名:

DimensionVersion.select("name").where(:dimension_id => 1).all.collect { |d| [d.name]}