-1

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

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

puts my_arr[0][0].to_a

为了让事情变得更简单,我将如何检索任何值,以便我可以将它放入普通变量中?

我正在使用带有 SQLite3 的 Rails 4。

4

4 回答 4

0

pluck已经返回一个数组 - 您不需要操作的输出

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

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

如果您有一个空数组 - 我保证您没有任何符合where条件的记录。这可能是由于title's 或artist' 名称中的一个小错字(开始与问题无关)。如果您确定您有符合过滤器的数据库对象 - 请务必仔细检查拼写错误,因为您的查询是正确的。

于 2015-12-06T09:55:27.157 回答
-1

看看这是否有帮助:

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
于 2015-12-06T03:22:53.747 回答
-1

您可以使用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}" }

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

于 2015-12-06T03:55:08.397 回答
-1

你可以试试这个:

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

希望这有帮助

于 2015-12-06T14:50:13.903 回答