SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Hybrid View

  1. #1
    SitePoint Zealot
    Join Date
    Mar 2001
    Location
    North Wales, UK
    Posts
    181
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Rails - "at least one" in a HABTM relationship

    I have products and categories, and a has_and_belongs_to_many relationship so that products can be in multiple categories. When adding a product, I want to ensure that the user selects at least one of the categories from the list.

    How do I go about this? I'm unsure whether it's something I have to specify in the relationship itself, or if it's something I can do using validates_presence_of in some way.

    Hopefully someone can point me in the right direction!

  2. #2
    SitePoint Addict
    Join Date
    Mar 2005
    Posts
    251
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    you have validates_associated :category
    which will check the integrity of the associated model.

  3. #3
    SitePoint Guru silver trophy Luke Redpath's Avatar
    Join Date
    Mar 2003
    Location
    London
    Posts
    794
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    validates_associated will only check the validity of an associated object if one exists. You want to uses associates_presence_of :associated_object to ensure one exists.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •