Validations not work fine with associations

Hello,

I thiks that rails validations not work fine with associations. For
example, if we have the models Antenna, Area and Position, where
positions are grouped by areas, areas has many antennas and antennas can
have positions. I want to validate that only antennas with an area can
be associated with positions, ie:

class Antenna < ActiveRecord::Base
belongs_to :area
has_and_belongs_to_many :positions

def validate
if area.nil? and positions.size > 0
errors.add(:positions, “The antenna must to…”)
end
end
end

But, although the validation send the error, the association is
performed:

p = Position.find(68)
p.antennas = []
=> []

a = Antenna.find(:first, :conditions => “area_id is null”)
a.positions << p
a.save
=> false

p = Position.find(68)
p.antennas.size
=> 1

p.antennas[0].id
=> 13

a.id
=> 13

There is a way for validate it? I think that it must to work with
scaffolding that manage associations (like Active Scaffold).

Daniel

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs