Prevent deleting foreign key

I’ve a Report and ReportType. The Report has one ReportType.
Now I want prevent deleting of used ReportTypes. This is my ReportType
class:

class ReportType < ActiveRecord::Base
validates_presence_of(:name);
has_many :reports
end

And my Report class:

class Report < ActiveRecord::Base
belongs_to :report_type,
:class_name => “ReportType”,
:foreign_key => “report_type_id”
end

I can create a query to find related reports, but I don’t think that’s
the right way. Can anyone help?

I can create a query to find related reports, but I don’t think that’s
the right way. Can anyone help?

That would be one option.
Do that in an before_destroy callback.

Option number two:
use a counter_cache.
Add a column report_count to ReportType
and define

belongs_to :report_type,
:class_name => “ReportType”,
:foreign_key => “report_type_id”,
:counter_cache => true

Then, again in before_destroy you can check for the number of records
without an extra query (and comes in useful in many other situations)

Then, again in before_destroy you can check for the number of records
without an extra query (and comes in useful in many other situations)

But can I also place a restrict on delete in my database and catch that
error?

On 23 May 2008, at 09:57, Sjoerd Schunselaar wrote:

Then, again in before_destroy you can check for the number of records
without an extra query (and comes in useful in many other situations)

But can I also place a restrict on delete in my database and catch
that
error?

Yes, create an actual foreign key constraint. rails won’t help you
there, but you can execute arbitrary sql in your migrations (or
anywhere else in fact), so just lookup foreign keys in the
documentation of your database.

Fred