9TrSl9IAlaLfDmffagsw
9TrSl9IAlaLfDmffagsw

Reputation: 405

Auto-create `belongs_to` record

Similar questions have been asked before but I just can't figure this out.

So I have Model_A and Model_B. Model_B belongs_to Model_A. What I want to do is when I create Model_A is to automatically call the create method for Model B. Then a script takes over a generates a bunch of data for Model_B. I use after_create because this only has to happen once.

It needs done this way. If you wanna know the details feel free to ask...

So I got Model_A here. I just can't seem to get the right syntax in create_model_b. In the example I used I just get an error saying the method doesn't exist for Model_A.

class Model_A < ActiveRecord::Base
  belongs_to :Model_B
  after_create :create_model_b

...

  def create_model_b
     #so I tried a bunch of stuff here but none of it worked
     #I need to create a Model_B which will contain the current Model_A id
     #ex. self.model_b.create(model_a_id: self.id)
  end
end

Model_B doesn't do anything special really:

class Model_B < ApplicationController
def create
    @model_b = Model_B.new(model_b_params)
    create_the_data

    respond_to do |format|
      if @model_b.save
           #redirect
      else
        #uh oh
      end
    end
  end
end

Thanks!

Upvotes: 0

Views: 294

Answers (2)

Yoonis
Yoonis

Reputation: 51

Your Model A contains half of an association: belongs_to :Model_B

Your Model B is missing its association to Model A.

Depending on the relationship you set up, you can complete the association with a has_one :Model_A, or has_many :Model_A, for example.

Here's Active Record documentation for reference.

Upvotes: 1

miler350
miler350

Reputation: 1421

Two ways:

1.

class Model_A < ApplicationController

def create
  @model_a = ModelA.new(model_a_params)
  if @model_a.save
    ModelB.create(model_a_id: @model_a.id, .....)
    #create data for model B either here or with after_create (of model B)
    redirect_to somewhere_awesome_path
  else
     # rescue error
     render 'new'
  end
end

2.

class Model_A < ActiveRecord::Base
  after_create :create_model_b

   ...

  def create_model_b
    ModelB.create(model_a_id: id)
  end
end

Upvotes: 1

Related Questions