Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6587023
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T16:51:54+00:00 2026-05-25T16:51:54+00:00

Is it possible to retrieve the child elements in a has_many association into a

  • 0

Is it possible to retrieve the child elements in a has_many association into a hash based on one of their properties?

For example, imagine a menu that has a single dish for each day:

class Menu
  has_many :dishes
end

and

class Dish
  belongs_to :menu
end

Dish has a key, day, which is one of either monday, tuesday etc. Is there some way to set up the has_many association such that Menu.dishes returns a hash similar to {:monday => 'spaghetti', :tuesday => 'tofu', ... }?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T16:51:55+00:00Added an answer on May 25, 2026 at 4:51 pm

    Sure. Something like this should suffice (assuming e.g. “spaghetti” is stored in a column called food).

    class Dish
      belongs_to :menu
    
      scope :by_day { select [ :day, :food ] }
    
      def self.by_day_hash
        by_day.all.reduce({}) {|hsh,dish| hsh[dish.day] = dish.food; hsh }
      end
    end
    
    class Menu
      has_many :dishes
    
      def dishes_by_day
        dishes.by_day_hash
      end
    end
    
    # Usage
    m = Menu.where( ... )
    m.dishes_by_day #=> { "monday" => "Spaghetti", "tuesday" => "Tofu" }
    

    So what’s happening here is that in Dish the by_day scope returns only two columns, day and food. It still, however, returns Dish objects rather than a Hash (because that’s what scopes do), so we define a class method, by_day_hash which takes that result and turns it into a Hash.

    Then in Menu we define dishes_by_day which just calls the method we made above on the association. You could just call this dishes but I think it’s better to keep that name for the original association since you might want to use it for other things later on.

    Incidentally (optional stuff below, skip for now if your eyes have glazed over), I might define by_day_hash like this instead:

    class Dish
      belongs_to :menu
    
      scope :by_day { select [ :day, :hash ] }
    
      def to_s
        food
      end
    
      def by_day_hash
        hsh = HashWithIndifferentAccess.new
        by_day.reduce(hsh) {|hsh, dish| hsh[dish.day] = dish }
      end
    end
    
    # Usage
    m = Menu.where( ... )
    m.dishes_by_day #=> { "monday" => #<Dish food: "Spaghetti", ...>, "tuesday" => #<Dish food: "Tofu", ...>, ... }
    

    …This way you still get the full Dish object when you call e.g. by_day_hash["monday"] but the to_s method means you can just drop it into a view like <%= @menu.dishes_by_day["monday"] %> and get “Spaghetti” instead of #<Dish day: "monday", food: "Spaghetti">.

    Finally, you might also notice I used HashWithIndifferentAccess.new instead of {} (Hash). HashWithIndifferentAccess is a class provided (and used everywhere) by Rails that is identical to Hash but lets you do either e.g. some_hash["monday"] or some_hash[:monday] and get the same result. Totally optional but very handy.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Is it possible to retrieve the size of the font used in a menu
is it possible to retrieve $_get's index name? eg. example.php?la=1&lala=2&lalala=3 how to print 'la',
Is it possible to retrieve items from a Python dictionary in the order that
Is it possible to retrieve variable set in onreadystatechange function from outside the function?
Is it possible to retrieve the underlying hostname/port from a new TcpClient? TcpListener listener
Is it possible to retrieve the geometric position (i.e. top/left offsets from either the
Is it possible to retrieve computer information (RAM, hard drive size, cpu speed, etc.)
is it possible to retrieve statistics about the minimal or maximal value of a
Is it possible to retrieve programmatically all the case of a switch ? I
is it possible to retrieve by using connection.getschema() the description item from a sql

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.