Ruby on rails 如何显示最新发布的?
所以,我有一个应用程序,允许用户上传歌曲并投票。投票数较高的歌曲最终排名靠前,新发布的歌曲需要投票才能在hackernews上看到 我也有一个“新歌”页面,我想显示新上传的歌曲,首先否定投票 “我的当前歌曲”控制器按如下方式对索引中的歌曲进行排序:Ruby on rails 如何显示最新发布的?,ruby-on-rails,ruby-on-rails-3,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 3,Ruby On Rails 4,所以,我有一个应用程序,允许用户上传歌曲并投票。投票数较高的歌曲最终排名靠前,新发布的歌曲需要投票才能在hackernews上看到 我也有一个“新歌”页面,我想显示新上传的歌曲,首先否定投票 “我的当前歌曲”控制器按如下方式对索引中的歌曲进行排序: def index @songs = Song.order('plusminus') end 我在song_控制器中有一个def new_songs操作,但我不确定如何让它只显示新歌并绕过投票。我对该gem了解不多,但它似乎是基于范围的
def index
@songs = Song.order('plusminus')
end
我在song_控制器中有一个def new_songs操作,但我不确定如何让它只显示新歌并绕过投票。我对该gem了解不多,但它似乎是基于范围的。正常查询数据怎么样
def new_songs
@songs = Song.order "id DESC"
end
或者更好,编写自己的范围:
# song.rb
scope :newest, order("id DESC")
# song_controller.rb
def new_songs
@songs = Song.newest
end
将包含最近从控制器操作上传的歌曲的实例变量传递到视图:
# 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
在视图中,您可以通过@latest_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