如何将API数据放入模型中?

问题描述 投票:0回答:2

当前,我正在使用Last.fm api在控制器中返回音乐会数据(返回哈希),并且在视图中循环浏览此哈希以返回所需的数据。我希望这些演唱会数据变得更加动态,并将所有内容放入模型中。我该怎么做呢?我应该在控制器中执行此操作还是在模型中执行此操作?

这是我的代码示例

# app/controllers/events_controller.rb
class EventsController < ApplicationController
  def index
    @events = @lastfm.geo.get_events("Chicago",0,5)
    respond_with @events
  end
end

# app/views/events/index.html.erb
<% @events.each do |event| %>
  Headliner: <%= event["artists"]["headliner"] %>
<% end %>

在此示例中,我希望使用带有顶篷作为参数的事件模型,并将所有5个事件放入此模型中。

ruby-on-rails api hash models
2个回答
0
投票

我相信拥有模型是一个好主意。我可以看到几个优点

1-您可以像其他对象一样以OO方式访问数据

2-如果您有一些业务逻辑(例如:计算),则可以在模型本身中完成而不会弄乱您的视图

3-干净且干燥

示例模型类将是(这不是一个有效的模型,只是为了给您一个想法):

class Event
  attr_accessor :headliner


  def self.event_list(limit = 5)
    lastfm.geo.get_events("Chicago",0,limit) 
  end

end

因此您可以将视图整理为

<% Event.each do |event| %>
   Headliner: event.headliner
<% end %>

0
投票

如果没有更多关于last.fm API的知识,很难彻底回答这个问题。通常,您希望将大多数复杂的逻辑和关系数据保留在模型中。

例如,您已经知道需要Event模型,但是看起来您可能也需要Artist模型。您可能最终会遇到这样的事情:

# app/models/artist.rb
class Artist
  attr_accessor :name

  def initialize(name)
    self.name = name
  end
end

# app/models/event.rb
class Event
  attr_accessor :artists

  def initialize(attributes)
    @attributes = attributes

    self.artists = attributes['artists'].map do |artist_name|
      Artist.new(artist_name)
    end
  end

  def headliner
    @headliner ||= self.artists.detect do |artist|
      @attributes['headliner'] == artist.name
    end
  end
end

# app/controllers/events_controller.rb
class EventsController < ApplicationController
  def index
    @events = @lastfm.geo.get_events('Chicago', 0, 5).map do |event_attributes|
      Event.new(event_attributes)
    end

    respond_with @events
  end
end

[您可能还想研究ActiveModel,它对没有数据库支持且不能从ActiveModel继承的模型具有一些有用的功能。

© www.soinside.com 2019 - 2024. All rights reserved.