多対多で has_many :through を使ったときの Association へのデータ追加法
多対多の関係で,has_many :through を使うとき,Association テーブルへデータを追加する方法の健忘録.
Association テーブルに何かしらデータを持たせるときには
book = Book.create
book.users << user
とすればいいのだが,create したくない状況での解決法としていろいろやってみると下記でうまく行った.
前提
class User < ActiveRecord::Base has_many :associations has_many :books, :through => :associations end class Book < ActiveRecord::Base has_many :associations has_many :users, :through => :associations end class Association < ActiveRecord::Base belong_to :user belong_to :book end
作成法
user = User.find(1) book = Book.new book.associations.build book.associations[0].eval = 10 book.save