Using Plucked Values in Ruby on Rails

末鹿安然 提交于 2019-12-13 08:28:03

问题


Given a model named Album, I want to use the values I pluck. For starters, I want to try to print the values. How can I do this? Here is my current code:

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

puts my_arr[0][0].to_a

To make things even simpler, how would I retrieve any value at all, so that I could place it into a normal variable?

I'm using Rails 4 with SQLite3.


回答1:


pluck already returns an array - you do not need to manipulate the output of

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

in any way - it is an array. In this case an array of 2-element arrays.

If you have an empty array - I guarantee you just do not have any records meeting the where conditions. It might be a result of a tiny typo in title's or artist's name whatsoever (which starts to be unrelated to question). If you are sure you have database objects that meet the filter - make sure to double check for typos, because your query is correct.




回答2:


See if this helps:

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



回答3:


You can use select to get an array of ActiveRecord models only with specified fields:

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

In this case the code is more readable.




回答4:


You can try with this :

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

Hope this helped



来源:https://stackoverflow.com/questions/34113578/using-plucked-values-in-ruby-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!