プログラミング的なSomething

プログラミング的なSomething

ITエンジニア(?)目線で生活・自転車・トレーニング話を綴ります

複数のbelongs_toを定義する

ユーザーに紐付く(例えばPickした)記事に紐づく単語を定義する。クラスはこんな感じ。

class User < ActiveRecord::Base
  has_many :articles
  has_many :tangos
end

class Article < ActiveRecord::Base
  belongs_to :user
  has_many :tangos
end

class Tango < ActiveRecord::Base
  belongs_to :user
  belongs_to :article
end

tangoをcreateするとエラーが返る。ネットを漁っているとsaveするタイミングが悪いみたいなので、createを使わないでbuildを使う。

user = User.first
article = user.articles.create
tango = article.tangos.create

#=> ActiveRecord::RecordNotSaved: You cannot call create unless the parent is saved

エラーも返らずいい感じ。

user = User.first
article = user.articles.create
tango = article.tangos.build

tango.user = user
tango.save