0

Currently I have a ReactJS application communicating with a Rails 5 API.

As part of this the React application makes a single JSON POST request to api/v1/job to create a new job record. This request includes information for two HABTM relationships with Tools and Technologies.

Job - has_and_belongs_to_many :technologies

Job - has_and_belongs_to_many :tools

How would I update the appropriate join tables in my rails controller with the ID's related to Job, Technologies and Tools?

The request looks as follows where the numbers are IDs:

{
   "job" : {
     ...
     "technologies" : [ "1", "6", "9" ],
     "tools" : [ "3", "5" ],
     ...
   }
}

It is worth mentioning that the request is sent as an axios POST request with JSON data so there are no traditional form fields.

I can also access the params successfully in my controller like so @technologies = params[job][technologies], i'm just unsure of the next step to create the record :)

Tom Pinchen
  • 2,467
  • 7
  • 33
  • 53
  • 1
    I think this should work: `job << Technology.where(id: params['job']['technologies'])`, this will create the records in join table considering that you have a single `job` object already. – Deepesh Apr 26 '18 at 12:03

1 Answers1

0

I eventually ended up with the following

@job['technology_list'].each do |tech|
    technology = Technology.find(tech['id'])
    @new_job.technologies << technology
end

In this instance @new_job is the job that was just created above in the controller.

Tom Pinchen
  • 2,467
  • 7
  • 33
  • 53