0
0

More than 3 years have passed since last update.

Rails モデルを紐付ける「関連(Association)」

Last updated at Posted at 2020-05-06

関連(Associationとは)

データベース上の紐付けを前提にして、モデルクラス同士の紐付けを定義することができる。
これにより、オブジェクト指向に沿った方法で関連するデータにアクセスすることができるようになる。

models/user.rb
class User
  has_many :tasks
end
models/task.rb
class Task
  belong_to :user
end

Userが親分、Taskが子分のイメージ。一つのUserに対して多くのTaskがぶら下がっていることを定義している。

何ができる?

この定義によってUserクラスのインスタンスに対しては、user.tasksといったメソッドで紐づいたTaskオブジェクトの一覧を得られることができる。

例) ログインしているユーザーのTaskデータの登録

task_controller.rb
def create
  @task = current_user.tasks.new(task_params)
end

参照

【初心者向け】丁寧すぎるRails『アソシエーション』チュートリアル【幾ら何でも】【完璧にわかる】🎸

0
0
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
0
0