Accessing associated models in a validate method

Why can’t I access an associated model in a validate method? I have
some code that looks like the following:

Models:
class Product < ActiveRecord::Base
has_many: upcs
end

class Upc < ActiveRecord::Base
belongs_to :product
def validate
errors.add_on_blank(‘upc’) unless product.new_record?
end
end

Controller:
def create
@product = Product.new(params[:product])
@upc = Upc.new(params[:upc])
@product.upcs << @upc unless @upc.upc.empty?

if @product.save
# …
end
end

When the create method gets called I get the NoMethodError “The error
occured while evaluating nil.new_record?” Why is product nil? How
can I access associated models in a validate method.

Thanks.

Eddie Hillenbrand wrote:

def validate
if @product.save
# …
end
end

When the create method gets called I get the NoMethodError “The error
occured while evaluating nil.new_record?” Why is product nil? How can
I access associated models in a validate method.

The “unless @upc.upc.empty?” code will stop @upc.product being set to
@product if upc is the empty string, so validate can’t see it. Why
don’t you remove this condition and add a “validates_associated :upcs”
line to Product, so that @product and its new upcs’s will only save if
everything’s valid.


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

Eddie Hillenbrand wrote:

Even with “unless @upc.upc.empty?” commented out “product” is still nil
in the validate method.

The requirements for the app are such that a product can be created
without a UPC, but once a product is saved a blank UPC can’t be added.
If you know a way to do this with the validation class methods, please
elaborate, I’d really like a better way to do this.

Is it that a product’s UPC can start off blank, but once it’s
set can’t return to being blank; or is it that the UPC must be
set no later than the first save after creation?

Also, try changing “product.new_record?” to “self.product.new_record?”.
That sometimes fixes these problems for reasons I can’t yet fathom.


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

On Feb 10, 2006, at 3:37 AM, Mark Reginald J. wrote:

The “unless @upc.upc.empty?” code will stop @upc.product being set to
@product if upc is the empty string, so validate can’t see it. Why
don’t you remove this condition and add a “validates_associated :upcs”
line to Product, so that @product and its new upcs’s will only save if
everything’s valid.

Even with “unless @upc.upc.empty?” commented out “product” is still
nil in the validate method.

The requirements for the app are such that a product can be created
without a UPC, but once a product is saved a blank UPC can’t be
added. If you know a way to do this with the validation class
methods, please elaborate, I’d really like a better way to do this.