davidhu
davidhu

Reputation: 10432

Saving two records in Rails at the same time where one has a foreign_key pointing to the other

class Pool
  has_many :memberships
end

class Membership
  belongs_to :pool, presence: true
end

This is the association I have. Whenever a new pool is created, I also want to create an entry into the membership class.

class Api::PoolsController < ApplicationController
  def create
    @pool = Pool.new(pool_params)
    member = Membership.new(user_id: current_user.id, pool_id: @pool.id)
    ...
  end
end

The issue is that @pool is not currently saved to the database yet, so it does not have an id value.

Is there a way that I can tell member to add the id after @pool is saved? Basically linking them to each other?

Upvotes: 0

Views: 41

Answers (1)

Michael Gorman
Michael Gorman

Reputation: 1077

class Api::PoolsController < ApplicationController
  def create
    @pool = Pool.new(pool_params)
    member = @pool.memberships.new(user_id: current_user.id)
    ...
  end
end

Upvotes: 1

Related Questions