LoginSignup
5
3

More than 5 years have passed since last update.

[Rails5] 既に存在するモデルに外部キーを追加しフォームで編集できるようにする

Last updated at Posted at 2017-06-23

やりたいこと

Rails5.1.1

  • ArticleモデルとCategoryモデルが既にある状態で、ArticleにCategoryをbelongs_toで紐付けたい。
  • ArticleモデルのフォームでCategoryを選択できるようにしたい

ArticleにCategoryへの外部キーを追加

Articleモデルに外部キーカラムを追加

category:referencesと指定することで、自動的にcategory_idカラムを追加してくれる。
category_id:referencesとやってしまうと、category_id_idというカラム名になってしまうので注意。

$ rails g migration add_category_to_article category:references

migration実行

$ rails db:migrate

一対多の関係を追記

複数のArticleでひとつのCategoryを使うので、こう。

app/model/article.rb
class Article < ApplicationRecord
  belongs_to :category
end
app/model/category.rb
class Category < ApplicationRecord
  has_many :articles
end

seeds.rbを使う場合

Articleを先に生成してしまうと、category_idがないよっていうエラーになるので注意。

db/seeds.rb
Category.create!(content: content)
Article.create!(title: title, category_id: 1)
$ rails db:migrate:reset
$ rails db:seed

フォームで編集できるようにする

※編集の場合
コントローラーは、普通に取得でOK

app/controllers/articles_controller.rb
def edit
  @article = Article.find(params[:id])
end

View側は今回セレクトボックスを使う引数は、
articleに追加したcategory_idフォームに表示したい要素群valueの値フォームに表示される文章オプション

app/views/form.html.erb
<%= f.collection_select(:category_id, Category.all, :id, :content, :prompt => true) %>

今回のオプション:promt => trueは、未選択時「Please select」を出すもの。newアクションでもこのまま使える

注意点

strong parametersにcategory_id追加を忘れないこと

app/controllers/articles_controller.rb
def article_params
  params.require(:article).permit(:title, :category_id)
end
5
3
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
5
3