它目前列出了我的最古老的文章在顶部,我想做相反的。我想我需要在某个地方订购它为created_at,但我还没有使它工作。我知道这很容易但我还是个新手。谢谢
目前我有
<div class="bit-75"><h2 id="title"><%= link_to article.title, article_path(article) %></h2>
<br>
<ul id="article-links">
<div id="article-image"><%= image_tag article.image_url %></div>
<br>
<li id="article-text"><%= article.text %></li>
<br>
<%= article.created_at %>
<br>
<% if admin_signed_in? %>
<li><%= link_to 'Edit', edit_article_path(article) %></li>
<li><%= link_to 'Destroy', article_path(article),
method: :delete, data: { confirm: 'Are you sure?'} %></li>
<li><%= link_to 'New article', new_article_path %></li>
<% else %>
<li><%= link_to 'Make a Comment', article_path(article) %></li>
</ul>
<% end %> article.rb
class Article < ActiveRecord::Base
has_many :comments, dependent: :destroy
validates :title, presence: true,
length: { minimum: 5 }
mount_uploader :image, ImageUploader
end物品控制器
def new
@article = Article.new
end
def index
@article = Article.all
end
def create
@article = Article.new(article_params)
if @article.save
redirect_to @article
else
render 'new'
end
end
def edit
@article = Article.find(params[:id])
end
def update
@article = Article.find(params[:id])
if @article.update(article_params)
redirect_to @article
else
render 'edit'
end
end
def show
@article = Article.find(params[:id])
end
def destroy
@article = Article.find(params[:id])
@article.destroy
redirect_to articles_path
end发布于 2014-06-27 18:57:43
在文章模型article.rb中,您可以设置如下所示的default_scope:
default_scope -> { order('created_at DESC') }但是,此方法将在所有页面上对此类文章进行排序。如果你只想在一个动作上像这样对它们进行排序,比如说你的def index,那么类似的事情可能会更好。
@articles = Article.order('created_at DESC')就像ShamsulHaque在他的评论中说的那样。
这里有一个关于默认作用域的很好的读物。
更新
如果您喜欢使用scopes (如@rich says ),那么语法如下所示:
scope :recent, ->(order = 'desc') { order(created_at: order.to_sym) }您可以选择在控制器中调用asc或desc,如下所示:
@articles = Article.recent('asc')
@articles = Article.recent('desc') # although we defaulted to 'desc', so really only need Article.recent为了解释一下,@rich包含了to_sym来将字符串'desc'或'asc'转换为像:desc或:asc这样的符号。如果您不这样做,您将得到一个错误,如
Direction should be :asc or :desc希望这能有所帮助。
发布于 2014-06-28 10:38:37
范围
使用default_scope是一种小禁忌 (可能会导致问题)--使用带有条件的标准范围要好得多:
#app/models/article.rb
Class Article < ActiveRecord::Base
scope :recent, (order = "desc") -> { where created_at: order.to_sym}
end这样你就可以打电话:
@article = Article.recent("asc")是对@justin答案的一个很好的扩展;)
https://stackoverflow.com/questions/24459002
复制相似问题