Question

How do I destroy the association itself and leave the objects being associated alone, while keeping this RESTful?

Specifically, I have these models:

class Event < ActiveRecord::Base
  has_many :model_surveys, :as => :surveyable, :dependent => :destroy, :include => :survey
  has_many :surveys, :through => :model_surveys
end

class ModelSurvey < ActiveRecord::Base
  belongs_to :survey
  belongs_to :surveyable, :polymorphic => true
end

class Survey < ActiveRecord::Base
  has_many :model_surveys
end

That's saying that the Event is :surveyable (ModelSurvey belongs_to Event). My question is, without having to create a ModelSurveysController, how do I destroy the ModelSurvey, while leaving the Event and Survey alone?

Something with map.resources :events, :has_many => :model_surveys? I'm not quite sure what to do in this situation. What needs to happen with the routes, and what needs to happen in the controller? I'm hoping the url could look something like this:

/events/:title/model_surveys/:id

Thanks for your help, Lance

Was it helpful?

Solution

In Rails 2.3 you have accepts_nested_attributes_for which would let you pass an array of ModelSurveys to the event in question. If you allow destroy through the nested attributes declaration, you'll be able to pass event[model_surveys][1][_destroy]=1 and the association will be removed. Check out the api docs.

OTHER TIPS

Resources domain != model domain


The domain of the controller is not the same as that of the models. It's perfectly fine to update multiple models by changing the state of a resource.

In your case that means doing a PUT or POST to either the Event or the Survey which contains a list of ids for the other. The model for one will update the association.

PUT or POST

Some people (but not Roy Fielding) believe that you should use a PUT to update the resource and provide all of the state again, others feel that a POST with the partial state (ala PATCH) is sufficient.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top