rails_admin handling foreign key failures
Asked Answered
P

2

6

I have a Rails4 application that uses rails_admin gem and MySql database.

I have a User model which has_many Jobs . Now, in rails_admin dashboard, User can be deleted normally, unless it has some Jobs. In that case foreign key fails because there is no dependent: :destroy defined on relation. This is intended behavior.

However, instead of getting "Cannot delete or update a parent row: a foreign key constraint fails" error I would like to show a nice message: "User can not be deleted if it has jobs".

Is there an elegant way to achieve this in rails_admin without making a custom action?

Pained answered 26/2, 2015 at 20:15 Comment(1)
You could try with a validation, the tough part is running this validation only for rails admin initiated changed. This would require messing with the params to send a custom param on rails admin user editing and then adding a attr_accessor on the user to match this param. Far from elegant.Necrology
A
2

You can't custom rails_admin's flash error messages, but you can cause an error and redirect to users's index page instead of raise an exception:

has_many :jobs, dependent: :restrict_with_error
Abilene answered 26/5, 2020 at 12:6 Comment(0)
F
1

Add foreign_key: { on_delete: :cascade } to your migration, for example:

class CreateComment < ActiveRecord::Migration[5.2]
  def change
    create_table :comments do |t|
      t.string :body
      t.references :post, foreign_key: { on_delete: :cascade }
      t.references :user, foreign_key: { on_delete: :cascade }

      t.timestamps
    end
  end
end
Foreandafter answered 6/12, 2018 at 2:11 Comment(2)
I don't want to cascade on delete, I just want to show a more user-friendly error message that it can't be deletedArther
May not answer OP's question, that delete cascade tip was exactly what I was looking for!Linson

© 2022 - 2024 — McMap. All rights reserved.