我想从我的数据库中获取5个最近的artilce的标题在ruby on rails上。我已经获取(获取所有文章标题)文章的标题,但这些不受此(最近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
articles_controller.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 %>
我尝试使用第一个或最后一个(5)获取,但没有奏效。如何获得5或10个最近的标题。请建议我。
答案 0 :(得分:2)
答案 1 :(得分:0)