validates_associated & foreign keys

Birgit (Westhawk)
Tue, 01 Jul 2008 12:06:06 -0000

Hi,

I''m struggling to get the validates_associated to work as I think it
should be.

I''m using:
JRuby 1.1
rails-2.0.2
activerecord-2.0.2
activerecord-jdbc-adapter-0.8.2


My tables in MySQL:
CREATE TABLE area_codes (
    id INT UNSIGNED auto_increment primary key
...
);

CREATE TABLE markets (
    id                  INT UNSIGNED auto_increment primary key,
...
);


CREATE TABLE area_codes_markets (
    id            INT UNSIGNED auto_increment primary key,
    market_id     INT UNSIGNED NOT NULL,
    area_code_id  INT UNSIGNED NOT NULL,
    INDEX(market_id),
    INDEX(area_code_id),
    CONSTRAINT UNIQUE (market_id, area_code_id),
    CONSTRAINT FOREIGN KEY(market_id)
        REFERENCES markets(id) MATCH FULL ON DELETE RESTRICT,
    CONSTRAINT FOREIGN KEY(area_code_id)
        REFERENCES area_codes(id) MATCH FULL ON DELETE RESTRICT
)
ENGINE=InnoDB;


My model:
class AreaCodesMarket < ActiveRecord::Base
  has_many :area_codes
  has_many :markets
  validates_associated      :area_codes
  validates_associated      :markets

  validates_presence_of     :area_code_id, :market_id
  validates_uniqueness_of   :market_id, :scope => :area_code_id
end


When I create a new area_codes_market record and (deliberately) enter
an area_code_id or a market_id that is incorrect, Ruby on Rails
doesn''t flag the error.
Instead I get an activerecord error on my foreign key constraint.

ActiveRecord::ActiveRecordError: Cannot add or update a child row: a
foreign key constraint fails
(`TestDoneRight_test`.`area_codes_markets`, CONSTRAINT
`area_codes_markets_ibfk_2` FOREIGN KEY (`area_code_id`) REFERENCES
`area_codes` (`id`)): INSERT INTO `area_codes_markets`
(`area_code_id`, `market_id`) VALUES(2, 1)

Reading the forums and the documentation, I think I have the correct
naming convention and model.

I found the following online
http://dev.rubyonrails.org/ticket/5369
However, the patch is for an older ActiveRecord version, so I''ve got
no idea how to apply it (assuming it would even work).

Does anyone have a clue how I could fix this?

Thanks, Birgit