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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With