我有一个显示相册和用户的应用程序
我目前正在输出专辑,
<main role="main" class="flex-shrink-0">
<div class="container">
<h1 class="mt-5">Albums</h1>
<p class="lead">Here we show all albums and it's details</p>
<div class="row">
<% @albums.each do |album| %>
<div class="col-md-4">
<%# image_tag(@albumImage ['thumbnailUrl']) %>
<h5 class="card-title">
<%= album['title'] %>
</h5>
<p>By: <%= album['userId'] %><p>
<%= link_to "View Album", album_path(album['id']), class: "btn btn-primary" %>
</div>
<% end %>
</div>
</div>
<%= will_paginate @albums, renderer: WillPaginate::ActionView::BootstrapLinkRenderer, class: 'margin-auto' %>
</main>
但是我想获取用户,以便我可以显示相册创建者的名称,目前,我正在显示相册用户ID
<p>By: <%= album['userId'] %><p>
理想情况下,我想做这样的事情
<p>By: <%= album.user['name'] %><p>
所有数据都来自外部API,在我拥有的控制器中
require 'will_paginate/array'
class AlbumsController < ApplicationController
def index
@albums = HTTParty.get('https://jsonplaceholder.typicode.com/albums', :headers => {'Content-Type' => 'application/json'}).paginate(:page => params[:page], :per_page => 10)
@user = HTTParty.get('https://jsonplaceholder.typicode.com/users', :headers => {'Content-Type' => 'application/json'})
end
end
不知道如何最好地解决这个问题。
> 首先,我假设@user
实际上是users
的array
。如果这是真的,你可能想做:
require 'will_paginate/array'
class AlbumsController < ApplicationController
def index
@albums = HTTParty.get('https://jsonplaceholder.typicode.com/albums', :headers => {'Content-Type' => 'application/json'}).paginate(:page => params[:page], :per_page => 10)
@users = HTTParty.get('https://jsonplaceholder.typicode.com/users', :headers => {'Content-Type' => 'application/json'})
end
end
然后,您应该能够执行以下操作:
<main role="main" class="flex-shrink-0">
<div class="container">
<h1 class="mt-5">Albums</h1>
<p class="lead">Here we show all albums and it's details</p>
<div class="row">
<% @albums.each do |album| %>
<div class="col-md-4">
<%# image_tag(@albumImage ['thumbnailUrl']) %>
<h5 class="card-title">
<%= album['title'] %>
</h5>
<p>By: <%= @users.find{|u| u['id'] == album['userId']}.try(:[],'name') || 'not available' %><p>
<%= link_to "View Album", album_path(album['id']), class: "btn btn-primary" %>
</div>
<% end %>
</div>
</div>
<%= will_paginate @albums, renderer: WillPaginate::ActionView::BootstrapLinkRenderer, class: 'margin-auto' %>
</main>
这:
@users.find{|u| u['id'] == album['userId']}
。将迭代@users
数组并找到具有与album['userId']
匹配id
的user
。
这:
.try(:[],'name')
。将尝试从找到的user
获取name
属性,但如果未找到user
,则不会引发和错误。
而这个:
|| 'not available'
。如果user
没有name
或找不到user
,将显示"不可用"。