Forum: Ruby on Rails What is wrong with validates_presence_of :my_association ?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
328f0bb678423fcea01ebe3b0edc74e6?d=identicon&s=25 Ben Johnson (benjohnson)
on 2009-01-09 01:13
Category.has_many :products

Let's say a product must belong to a category. I know it is recommended
to do the following:

class Product
validates_presence_of :category_id
end

But, as we all know, this is a pain for new records, meaning what if the
associated category is a new record?

I've been meaning to ask this, but what's wrong with doing the
following:

class Product
validates_presence_of :category
end

I never understood why that was so wrong. So I wanted to ask and see if
I am missing something. What do you think? Thanks for your help!
9a2a53db8e9b4476038c94a64b32833f?d=identicon&s=25 Ryan Bigg (ryan-bigg)
on 2009-01-09 01:59
(Received via mailing list)
That will check the value for a field called category, not an
association.
-----
Ryan Bigg
Freelancer
http://frozenplague.net
8853f712852b03ba6646b59b1723f44d?d=identicon&s=25 Flower Born (flowerborn)
on 2009-01-09 02:52
(Received via mailing list)
* Ben Johnson <rails-mailing-list@andreas-s.net> [2009-01-09 01:13:53
+0100]:

> But, as we all know, this is a pain for new records, meaning what if the
> associated category is a new record?
>
> I've been meaning to ask this, but what's wrong with doing the
> following:
>
> class Product
> validates_presence_of :category
> end

In this case you may need validates_associated or write your own
validation by def validate.
C64e63b70be7dfed8b0742540b8b27e5?d=identicon&s=25 Mark Reginald James (Guest)
on 2009-01-09 03:03
(Received via mailing list)
Ben Johnson wrote:
> associated category is a new record?
>
> I've been meaning to ask this, but what's wrong with doing the
> following:
>
> class Product
> validates_presence_of :category
> end
>
> I never understood why that was so wrong. So I wanted to ask and see if
> I am missing something. What do you think? Thanks for your help!

It isn't wrong, it's the right way to do it. You just have to
assign a category object when building a new Product.

--
Rails Wheels - Find Plugins, List & Sell Plugins -
http://railswheels.com
This topic is locked and can not be replied to.