LoginSignup
5
5

More than 5 years have passed since last update.

buildを使って複数のアクティブレコードのオブジェクトを作成する。

Posted at

環境はRails 4.2.2

buildを使って複数のアクティブレコードのオブジェクトを作成する。

テーブルの関係はuserとtagsが1:n。
Modelは下記のような感じで関連付け(アソシエーション)を指定する。

user.rb
class User < ActiveRecord::Base
  has_many :tags
end
tag.rb
class tag < ActiveRecord::Base
  belongs_to :user
end

あとは下記のようにbuildメソッドに配列を渡してやれば、Userに紐付けたTagモデルのActive Record配列が取得できる。

@user = User.first
@tags = @user.tags.build([{ name: "Ruby"}, { name: "Haskell"},{ name: "Lisp"}])
# => [#<Tag id: nil, user_id: 1, name: "Ruby", created_at: nil, updated_at: nil>, #<Tag id: nil, user_id: 1, name: "Haskell", created_at: nil, updated_at: nil>, #<Tag id: nil, user_id: 1, name: "Lisp", created_at: nil, updated_at: nil>]
5
5
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
5