amoks
amoks

Reputation: 103

Accessing model information inside an array

In my rails application I am making a call to a third party API that returns 3 different artists. I want to first save the records if they don't exist in ActiveRecord, and then show the same records in my view, but taken from ActiveRecord, not the API call.

My first thought was to create an array that would keep all the e_id, and then use the same e_id to do a where search.

The array ends up getting the right artists from the database, but when trying to access the information it just comes up with the model information. For example, s.name would return "Artist".

Any ideas how to solve this?

Controller:

apicall = API.artist_similar(:id => band.e_id, :results => 3)
@similar_artists = []

echonest_similar.each do |artist|
    if Artist.exists?(:e_id => artist.id)
        apicall.delete(band)
    else
        newartist = Artist.new(:name => artist.name, :echo_id => artist.id)
        newartist.save
    end
    @similar_artists << Artist.where(:e_id => artist.id)
end

View:

<% @similar_artists.each do |s| %>  
    <h4><%= s.name %></h4>
<% end %>

Upvotes: 0

Views: 42

Answers (1)

Anthony
Anthony

Reputation: 15967

You're hitting the database a few too many times here. What you can do is use ActiveRecord#first_or_create:

apicall = API.artist_similar(:id => band.e_id, :results => 3)
@similar_artists = []

echonest_similar.each do |artist|
  @similar_artists << Artist.first_or_create(name: artist.name, echo_id: artist.id)
end

Upvotes: 2

Related Questions