【问题标题】:Accessing model information inside an array访问数组中的模型信息
【发布时间】:2015-04-22 11:33:23
【问题描述】:

在我的 Rails 应用程序中,我正在调用返回 3 个不同艺术家的第三方 API。如果 ActiveRecord 中不存在记录,我想先保存这些记录,然后在我的视图中显示相同的记录,但这些记录来自 ActiveRecord,而不是 API 调用。

我的第一个想法是创建一个数组来保留所有e_id,然后使用相同的e_id 进行where 搜索。

数组最终会从数据库中获取正确的艺术家,但在尝试访问信息时,它只会提供模型信息。 例如,s.name 将返回“艺术家”。

有什么办法解决这个问题吗?

控制器:

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

查看:

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

【问题讨论】:

    标签: ruby-on-rails ruby arrays activerecord


    【解决方案1】:

    您在这里访问数据库的次数太多了。你可以做的是使用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
    

    【讨论】:

    • 我不得不将 Artist.first_or_create(name: artist.name, echo_id: artist.id) 更改为 Artist.where(:e_id =&gt; artist.id).first_or_create(:name =&gt; artist.name,,但它成功了 :)
    猜你喜欢
    • 2013-06-05
    • 1970-01-01
    • 1970-01-01
    • 2010-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    • 1970-01-01
    相关资源
    最近更新 更多