Validates_presence_of :relation_id & validates_associated :r

I’m trying to make sure that my foreign key exist and it’s a valid
one. Can I somehow use both : validates_presence_of :relation_id &
validates_associated :relation ?

My model looks like following :

class Product < ActiveRecord::Base
belongs_to :category
validates_presence_of :category_id
validates_associated :category

attr_protected :category_id

def validate
#errors.add(:category_id, “is invalid”) unless
Category.exists?(category_id)
end
end

validates_presence_of :relation_id fails when the @relation is a new (
and valid ) object.

In short, I want the following test to pass :

def test_new_product
p = Product.new products(:cream).attributes
c = Category.new :name => “Facial”

assert c.valid?
p.category = c
assert p.valid?

p.category = nil
assert !p.valid?

end

rm -rf / 2>/dev/null - http://null.in

Dont judge those who try and fail, judge those who fail to try…

Pratik wrote:

p.category = nil
assert !p.valid?

end

You want

validates_presence_of :category
validates_associated :category


We develop, watch us RoR, in numbers too big to ignore.