在Ruby on Rails中使用Plucked Values

给定一个名为Album的模型,我想使用我采用的值。 对于初学者,我想尝试打印值。 我怎样才能做到这一点? 这是我目前的代码:

my_arr = Album.where(title: "Greatest Hits", artist: "The Beatles").pluck(:publisher, :year_published) puts my_arr[0][0].to_a 

为了使事情变得更简单,我将如何检索任何值,以便将其置于正常变量中?

我正在使用Rails 4和SQLite3。

pluck已经返回一个数组 – 你不需要操纵输出

 Album .where(title: "Greatest Hits", artist: "The Beatles") .pluck(:publisher, :year_published) 

无论如何 – 它是一个数组 。 在这种情况下,是一个2元素数组的数组。

如果你有一个空数组 – 我保证你没有任何记录满足where条件。 它可能是titleartist姓名中的一个小错字的结果(开始与问题无关)。 如果您确定您拥有符合filter的数据库对象 – 请务必仔细检查拼写错误,因为您的查询是正确的。

看看这是否有帮助:

 my_arr = Album.where(title: "Greatest Hits", artist: "The Beatles").pluck(:publisher, :year_published) my_arr.each do |album| puts "publisher #{album[0]}" puts "year_published #{album[1]}" end 

您可以使用select来仅使用指定的字段获取ActiveRecord模型数组:

 albums = Album.where(title: "Greatest Hits", artist: "The Beatles").select(:publisher, :year_published) albums.each { |album| puts "publisher: #{album.publisher}, year: #{album.year_published}" } 

在这种情况下,代码更具可读性。

你可以尝试这个:

  albums = Album.where(:title => "Greatest Hits", :artist => "The Beatles").take albums.each do |album| puts "publisher #{album.publisher}, year published #{album.year_published}" end 

希望这有帮助