我想从我的 ruby on rails 数据库中获取 5 个最新的文章标题。我已经获取(获取所有文章的标题)文章的标题,但不受此(5 个最近的)条件的限制。在控制器或模型部分中写入此逻辑的位置。如果它应该写在模型中,那么如何在视图部分中访问它。是否会写在控制器部分。请给我建议。
文章模型
class Article < ActiveRecord::Base
attr_accessible :title, :body
attr_accessible :tag_list
has_many :comments
belongs_to :user
has_many :taggings
has_many :tags, through: :taggings
validates :title, :body, :tag_list, :presence => true
def tag_list
self.tags.collect do |tag|
tag.name
end.join(", ")
end
def tag_list=(tags_string)
tag_names = tags_string.split(",").collect{|s| s.strip.downcase}.uniq
new_or_found_tags = tag_names.collect { |name| Tag.find_or_create_by_name(name) }
self.tags = new_or_found_tags
end
end
文章控制器.rb
class ArticlesController < ApplicationController
before_filter :is_user_admin, only: [:new, :create, :edit, :destroy]
def is_user_admin
redirect_to(action: :index) unless current_user.try(:is_admin?)
return false
end
def index
@articles = Article.all(:order => "created_at DESC")
end
def show
@article = Article.find(params[:id])
end
def new
@article = Article.new
end
def create
@article = Article.new(params[:article])
@article.user_id = current_user.id
if @article.save
flash[:success] = "article created!"
redirect_to article_path(@article)
else
render 'new'
end
end
def destroy
@article = Article.find(params[:id])
@article.destroy
redirect_to action: 'index'
end
def edit
@article = Article.find(params[:id])
end
def update
@article = Article.find(params[:id])
if @article.update_attributes(params[:article])
flash.notice = "Article '#{@article.title}' Updated!"
redirect_to article_path(@article)
else
render 'edit'
end
end
end
文章/index.rb
<div style="background-color:#1fb2e8; color:#FFFFFF; font-size: 1.6em"> recent article </div>
<div style="font-size: 1.3em">
<% @articles.each do |article| %>
<div style="margin-top:15px; margin-left:8px"> <%= link_to article.title.first(5), article_path(article) %></div>
<% end %>
我尝试使用 first 或 last(5) 获取,但没有成功。如何获得 5 或 10 个最近的标题。请给我建议。