SitePoint Sponsor

User Tag List

Results 1 to 2 of 2

Hybrid View

  1. #1
    Formerly known as RockNRollPig Shpigford's Avatar
    Join Date
    Dec 2002
    Location
    Denver, CO
    Posts
    2,877
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question Issue with associations

    I have a categories table that has parent categories and sub categories that are attached via "parent_id"

    I then have items that are attached to the specific category via "category_id".

    My associations:
    Item belongs_to Category
    Category has_many Items

    The item really always has a category_id that matches one of the sub categories but there are places where I need to get parent category as well.

    So my question is how can I get the parent category?

    Right now if I want the sub category I just do item.category.title (which works because of my association)...but I want to be able to do something like item.category.parent_id.title so I can get the title of the main parent category.

    Any ideas?

  2. #2
    SitePoint Enthusiast thebasti's Avatar
    Join Date
    Aug 2004
    Location
    Novi Sad, Serbia
    Posts
    60
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    What you need is a self referential category model. You probably want something like this in your category model:

    Code Ruby:
    belongs_to :parent, :class_name => "category", :foreign_key => "parent_id"
    has_many :sub_categories, :class_name => "category", :foreign_key => "parent_id"

    Once you have that you'll be able to do:

    Code Ruby:
    item.category.parent.title
    "Strategy without tactics is the slowest route to victory.
    Tactics without strategy is the noise before defeat."
    - Sun Tzu
    Icebergist - a web dev blog | Orange Iceberg Web App Development


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
  •