【发布时间】:2021-03-04 10:50:01
【问题描述】:
我正在使用这个 GiantBomb API(https://github.com/games-directory/api-giantbomb) 来获取游戏列表。用户搜索游戏,然后将其添加到他们的库中。用户还可以查看其他人的图书馆。我让它工作,除了我添加到库中的项目无法调用所有 API 数据。我想将 GiantBomb::Game 数据放入一个 has 中,这样我就可以在视图中调用数据,例如 @game.description 等等。
这是我的游戏控制器。有一个搜索功能、单个游戏的显示页面,以及将单个游戏添加到用户库页面的我的库功能。
class GamesController < ApplicationController
#Users search for games
def index
@games = GiantBomb::Search.new().query(params[:query]).resources('game').limit(100).fetch
end
#individual game profile page
def show
@game = GiantBomb::Game.detail(params[:id])
end
#Adding games to user libraries
def library
type = params[:type]
@game = Game.new(game_params)
if type == "add"
current_user.library_additions << @game
redirect_to user_library_path(current_user), notice: "Game was added to your library"
elsif type == "remove"
current_user.library_additions.delete(@game)
redirect_to root_path, notice: "Game was removed from your library"
else
# Type missing, nothing happens
redirect_to game_path(@game), notice: "Looks like nothing happened. Try once more!"
end
end
private
def game_params
params.require(:game).permit(:name, :id)
end
end
将游戏添加到库中查看此代码在视图中。
<% if user_added_to_library?(current_user, game) %>
<%= link_to 'Remove from library', add_game_path(game['id'], type: "remove", game: game), method: :put %>
<% else %>
<%= link_to 'Add to library', add_game_path(game['id'], type: "add", game: game), method: :put %>
<% end %>
在我的展示页面上,我通过 GiantBomb::Game.detail(params[:id]) 直接从 API 中提取,所以我可以调用如下参数:
<div class="cards">
<div class="card">
<%= image_tag @game.image['medium_url'], class: "cover"%>
<div class="container">
<h2><%= @game.name %></h2>
<p><%= @game.deck %></p>
<p><%= @game.id %></p>
<% if @game.platforms === nil %>
<p>Platform Unknown</p>
<% else %>
<p><%= @game.platforms[0]['name'] %></p>
<% end %>
<p><%= @game.original_release_date.to_s[0..3] %></p>
</div>
</div>
</div>
但是,我的库函数不能使用@game = GiantBomb::Game.detail(params[:id]),我必须使用@game = Game.new(game_params)。我的游戏模型只有 name 和 id 与之关联,所以我似乎只能在库页面上显示该信息。
这是我的图书馆控制器。
class LibraryController < ApplicationController
#find user id through params
def index
@library_games = User.find(params[:id]).library_additions
end
end
这是索引页:
<h1>Library</h1>
<% if @library_games.exists? %>
<% @library_games.each do |game| %>
<div class="container">
<p><%= game.name%></p>
<p><%= game.id %></p>
</div>
<% end %>
<% else %>
<div class="container">
<div class="message-body">You haven't added any games to your library yet. <%= link_to 'Add some', root_path %>.</div>
</div>
<% end %>
如果我使用 game.deck,我会得到一个未定义的方法,但如果我使用 game['deck'],我不会收到错误消息,但在我的显示页面中没有显示任何内容。
所以我是否需要为我的游戏模型中的每个单独的数据(甲板、图像、平台等)添加迁移,或者有没有办法编辑我的库方法以便我可以传递所有 GiantBomb: :游戏数据到我的 library_additions 中,这样我就可以通过@game.insertdatahere 调用任何数据?
【问题讨论】:
标签: ruby-on-rails api hash