I want to fetch 5 most recent artilce's titles from my db in ruby on rails. I have already fetched( fetch all article' title) article's title but those are not restricted by this (5 most recent) condition. Where to write to this logic, either in controller or in model part. If it should be written in model then how to access it in views part. Whether it will be written in controller part. Please suggest me.
article model
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
article/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 %>
I tried to fetch using first or last(5), but did not worked. How to get 5 or 10 recent titles. Please suggest me.