Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails_admin handling foreign key failures

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?

like image 893
Igor Pantović Avatar asked Feb 26 '15 20:02

Igor Pantović


2 Answers

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
like image 158
Cong Chen Avatar answered Oct 25 '22 02:10

Cong Chen


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
like image 28
Artur Haddad Avatar answered Oct 25 '22 00:10

Artur Haddad