5

I have a Rails 4.1 application which is using a few notable technologies.

Simple Form, Cocoon

I'm having trouble destroying records which are nested attributes. Based on some lengthy research, I believe my code is correct, however I may be missing something silly.

Model

has_many :staff_services_joins, :dependent => :destroy
has_many :services, :through => :staff_services_joins
accepts_nested_attributes_for :staff_services_joins, :allow_destroy => true

It's a little unorthodox, but I have two components on the join model which are not foreign keys and need to be set. That is why I'm accepting nested attributes for the join model rather than the service model.

Controller Method

def update
ap staff_params
# if @staff_member.update_with_account staff_params, params[:password]
if @staff_member.update_attributes staff_params
  flash[:notice] = 'Successfully updated staff member! :)'
  redirect_to vendor_store_staff_path current_store, @staff_member
else
  flash[:error] = 'Failed to update staff member :('
  render :edit
end end

Strong parameters

params.require(:staff).permit(
    :user_id,
    :store_id,
    :avatar,
    :remote_avatar_url,
    :first_name,
    :last_name,
    :email,
    :active,
    :admin,
    :staff_services_joins_attributes => [
        :staff_id,
        :service_id,
        :price,
        :duration,
        :_destroy
    ]
)

Example update params hash

{
"store_id" => "2",
"avatar" => "avatar.png",
"remote_avatar_url" => "",
"first_name" => "Joshua",
"last_name" => "Tyree",
"email" => "joshuat@createthebridge.com",
"active" => "0",
"admin" => "1",
"staff_services_joins_attributes" => {
    "0" => {
        "service_id" => "2",
        "price" => "50.00",
        "duration" => "30",
        "_destroy" => "1"
    }
}

}

Based on the has, this thing should be destroying that model, but for some reason it certainly isn't. Any help is most definitely appreciated.

Joshua Tyree
  • 73
  • 1
  • 5
  • 2
    well just add `:id` inside the `staff_services_joins_attributes: [..` and try. – Arup Rakshit Apr 06 '15 at 13:06
  • Interesting, that did solve the problem. Just so I understand why, is it because ActiveRecord has no way of discerning what record that relates to in the database by way of the array index? – Joshua Tyree Apr 06 '15 at 13:18

1 Answers1

18

In order to use accepts_nested_attributes_for with Strong Parameters, you will need to specify which nested attributes should be whitelisted. You did it, but you missed to add :id which is needed to perform the deletion operation. "_destroy" key marked the record for deletion, but to find the record out and delete internally, it needs to have :id present there.

You can read Removing Objects guide.

Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317