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

时间:2012-06-28 04:45:59

标签: ruby-on-rails api hash models

目前我正在使用Last.fm api在我的控制器中返回Concert数据(返回一个哈希),并在视图中循环访问此哈希以返回我想要的数据。我希望这个音乐会数据变得更加动态,并将所有内容都放入模型中。我该怎么做呢?我应该在控制器中还是以某种方式在模型中执行此操作?

以下是我的代码

的示例
# 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个事件放入此模型中。

2 个答案:

答案 0 :(得分: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 %>

我想你明白我的观点:)

答案 1 :(得分: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,它对于非数据库支持且无法从ActiveRecord::Base继承的模型具有一些有用的功能。