Dave Castellano wrote in post #1110796:
Here you are destroying the picture object so naturally Rails will
manage the associations automatically. What you want to do instead is
to delete the association not the actual picture object.
There are a couple of ways to do this. But, you do not wan to use the
destroy action on pictures_controller. That action should be used to
destroy pictures not associations.
Option 1—Expose the join model and manage the association with standard
REST destroy action on the association model:
class Picture < ActiveRecord::Base
has_many :question_pictures
has_many :questions, :through => :question_pictures
end
class Question < ActiveRecord::Base
has_many :question_pictures
has_many :pictures, :through => :question_pictures
end
class QuestionPicture < ActiveRecord::Base
belongs_to :question
belongs_to :picture
end
question_pictures_controller
-----------------
def destroy
question_picture = QuestionPicture.find(params[:id])
question_picture.destroy
end
Option 2—Add an additional RESTful action to questions_controller
config/routes.rb
-------------------
resources :questions do
delete 'remove_picture', :on => :member
end
questions_controller.rb
-------------------
def remove_picture
question = Question.find(:id)
picture = question.pictures.find(params[:picture_id])
question.pictures.delete(picture)
end
Example URL:
DELETE:
http://example.com/galleries/1/remove_picture/?picture_id=1
P.S. None of this code has been tested. Just wrote it by memory.