22
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Controller名と異なる他Modelのメソッドを使う方法

Posted at

今まで、Model名と同名のControllerでないとメソッドが使えないと思い込んでいた。

要するに、item.rbというModelがあって、item.rbで設定されたメソッドを使えるのは
items_controller.rbのみだと勘違いしていた。

でも、そんな事はないという事が分かったので、理解出来ている範囲でまとめてみる。

index_controller.rbというControllerがあったとする。

class IndexController < ApplicationController
  def index
    @items = Item.all.order("updated_at DESC").limit(30)
  end
end

このようにItemというモデル名を記述してあげれば、item.rbに設定されたメソッドやforeign_keyのIDなども
アクセスする事が出来る。

22
13
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
22
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?