Loading ...
Sorry, an error occurred while loading the content.

226fk's ref int (AR)

Expand Messages
  • Edwin Pratomo
    Aug 19, 2005
    • 0 Attachment
      sebetulnya bagaimana cara membuat referential integrity utk fk, Rails way?
      kalo cara begini rasanya kok masih ribet. ada cara yg lebih ringkas, elegan?

      class User < ActiveRecord::Base
      has_many :request
      validates_presence_of :name

      # on delete cascade
      before_destroy :destroy_referencing_requests

      def self.id_exists?(id)
      !find_first(["id = %d", id]).nil?
      end

      protected
      def destroy_referencing_requests
      Request.delete_all(["user_id = %d", id])
      end
      end

      class Request < ActiveRecord::Base
      belongs_to :user
      validates_presence_of :reason, :user_id

      protected
      def validate_on_create
      unless User.id_exists?(user_id)
      errors.add("id", "not found in users")
      end
      end

      def validate_on_update
      unless User.id_exists?(user_id)
      errors.add("id", "not found in users")
      end
      end
      end

      __END__

      rgds,
      Edwin.