I have two models that I want to manually associate or dissociate on demand.
class Car < ApplicationRecord
has_many :wheels, dependent: :nullify
end
class Wheel < ApplicationRecord
belongs_to :car
end
Say that my database is already full of cars and wheels. I don't know what is the proper way to associate a wheel to a car using JSON API calls or dissociate one in case a wheel have already a car_id filled.
Should I just create a nested route such as :
resources :cars do
resources :wheels, only: [:add_to_car, :remove_from_car]
end
But the add_to_car and remove_from_car methods doesn't show up in the routes list.
Ideally I would like to do something like /cars/:id/add_wheel/:wheel_id (or something like that more RESTful friendly)
What is the Rails way to do this?
Ir order to define this routes:
You can do something like this
Then your controller should look like this:
Anyway, there is another approach even more RESTFUL, because if you see the previous answer, you can notice that there is a perform over the wheel, and that is not very RESTful. But if you have your model like:
Then in your controller you can write st like this:
The other thing is you can consider is having routes like
And the controller:
At the end, it depends on you and how you think your application domain!