Jump to content

The ultimate community for Ruby on Rails developers.


Photo

Associating one object from has_many collection

ruby collections associations has_many has_one

  • Please log in to reply
2 replies to this topic

#1 MarsChelios

MarsChelios

    Passenger

  • Members
  • 2 posts

Posted 09 March 2014 - 06:53 PM

I have four models and I am struggling building associations for the last one.

class Color < ActiveRecord::Base
  has_many :games, through: :game_colors
end

class GameColor < ActiveRecord::Base
  belongs_to :game
  belongs_to :color
end

class Game < ActiveRecord::Base
  has_many :game_colors
  has_many :colors, through: :game_colors

  has_many :images
end

class Image < ActiveRecord::Base
  belongs_to :game
  #associates with one :color from the :game_colors in :game
end

I have the relationship between Color and Game working well through GameColor; I can save/update in a game with no issues. What I am trying to do now is to build an association with one of the colors in the game_colors collection in game to the Image model.

 

There will be multiple Image instances that will have the same color associated with it. I feel like this is doable from reading through the associations docs but I'm still new to Rails and can't figure out the exact method.

 

If you suggestions for alternative ways to model this I'd love to hear that as well.



#2 MarsChelios

MarsChelios

    Passenger

  • Members
  • 2 posts

Posted 09 March 2014 - 08:07 PM

For the time being I am storing the id of the color in the database and retrieving it as below, but it would still be nice (more efficient?) to have this be done through AR associations.

class Image < ActiveRecord::Base
  belongs_to :game

  def color
    self.game.colors.find(self.color_id)
  end
end


#3 james

james

    Guard

  • Moderators
  • 223 posts
  • LocationLeeds, U.K.

Posted 10 March 2014 - 09:10 AM

You haven't really described your requirements and use cases so it is very difficult to know what you want to do

I think what you are describing is each image can have only a single colour

An image can be re-used in multiple games? If an image has a game as it's foreign key this is not possible! so I assume I have that wrong

 

Anyway the answer to your immediate problem is to associate the image with the game_color on a has_one and belongs_to relationship. I don;t know enough about your requirements to say which way the belongs_to should be

 

Tip

When designing your database think only about the database not about the code


Programming is just about problem solving!






Also tagged with one or more of these keywords: ruby, collections, associations, has_many, has_one

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users