luca
luca

Reputation: 12601

active record: create record from parent object

this is what I mean:

job has many docs. I want to create a doc, I can do:

@doc = Doc.new(params[:doc])

but I'd like to enforce the parent-child relationship, since I already know the job.. something like this:

@job.docs.new(params[:doc])

so that the job_id field gets ignored and only the @job object matters...

does it make any sense?

Upvotes: 1

Views: 3521

Answers (3)

Greg Campbell
Greg Campbell

Reputation: 15292

You should be able to use the build method:

@job.docs.build(params[:doc])

See the has_many api documentation or the Rails Guide for associations for a list of methods available on the collection.

Upvotes: 4

Simone Carletti
Simone Carletti

Reputation: 176352

# initialize the object
@job.docs.build(params[:doc])
# create the object
@job.docs.create(params[:doc])

Upvotes: 4

Pesto
Pesto

Reputation: 23880

As long as you've specified the relationship in the model, Job will automagically have a build method:

@job.docs.build(params[:doc])

Upvotes: 1

Related Questions