LoginSignup
3
4

More than 5 years have passed since last update.

Railsでテーブルデータ処理が頻繁に出てくる時はscopeを使う

Last updated at Posted at 2013-01-29

今日勉強したメモ。
テーブルデータの検索で頻繁に使う処理はscopeを使って、定義しておくのがいいみたい。

(例)記事一覧が最新記事順で並べられるようにEntryクラスにscopeを追加する

【モデル】
定義する
./app/models/entry.rb
:latestとシンボルを設定。

class Entry < ActiveRecord::Base
  scope :latest , order ('update_at desc')
end

【コントローラー】
./app/controller/entries_controller.rb

class EntriesController < ApplicationController
  def index
    @entries = Entry.where("blogger_id=?" , @blogger.id).latest 
  end
end
3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4