1

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

article_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 %>

first または last(5) を使用して取得しようとしましたが、うまくいきませんでした。最近のタイトルを 5 つまたは 10 タイトル取得する方法。私に提案してください。

4

2 に答える 2