将包含控制器操作中最近上传的歌曲的实例变量传递给视图:
# app/controllers/songs_controller.rb
def index
@songs = Song.order('plusminus')
@newest_songs = Song.order('created_at DESC').limit(10) # returns the ten most recently uploaded songs
end
在视图中,您可以通过@newest_songs
实例变量访问十首最新的歌曲:
# app/views/songs/index.html.erb
<h1>Highest Voted Songs</h1>
<% @songs.each do |song| %>
# view logic
<% end %>
<h1>Newest Songs</h1>
<% @newest_songs.each do |song| %>
# view logic
<% end %>
或者,如果您想通过完全独立的视图显示最新歌曲,您可以执行类似于以下操作:
# app/controllers/songs_controller.rb
def new_songs
@songs = Song.order('created_at DESC')
end
# app/views/songs/new_songs.html.erb
<h1>Newest Songs</h1>
<% @newest_songs.each do |song| %>
# view logic
<% end %>
# config/routes.rb
resources :songs do
collection do
get 'new_songs' # creates route from `songs/new_songs` to the `songs#new_songs` controller action
end
end