Ruby on Railsのアソシエーションについて勉強中です。
実現したいシステムは以下です。(上司から出された課題です)
Authorは複数のBookを持っている Bookは複数のReviewを持っている それぞれのモデルは Author(name: string, age: integer) Book (author_id: references, title: string, price:integer, published_at: datetime) Review (book_id: references, title: string, body: string)
Authorモデルはログイン機能を搭載するため、既にdeviseで作成済みです。
これに対して、
rails g model Book author_id: reference title: string price: integer published_at: datetime
rails g model Review book_id: reference title: string body: string
の後
rails db:migrate
でモデルを作成しました。
Author.rb, Book.rb, Review.rbの中身は以下のようになっています。
Author
1class Author < ApplicationRecord 2 # Include default devise modules. Others available are: 3 # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable 4 devise :database_authenticatable, :registerable, 5 :recoverable, :rememberable, :validatable 6 7 after_create :send_welcome_mail 8 9 has_many :books 10 11 def send_welcome_mail 12 AuthorMailer.author_welcome_mail(self).deliver 13 end 14end
Book
1class Book < ApplicationRecord 2 3 has_many :reviews 4 5 belongs_to :author_id 6 7end
Review
1class Review < ApplicationRecord 2 belongs_to :book_id 3end
ここで質問なのですが、rails consoleを起動し、Book.new
で新しく本を作成しようと思ったのですが、author_idの値をどのように扱えば良いのかわかりません。
book = Book.new(author_id: 1)
としてもエラーが出てしまいます。扱い方を教えていただきたいです。それ以前にreference型の理解も浅い状態です。。。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。