Search code examples
ruby-on-rails-3activerecordassociationsmodels

Association between one model and an attribute of another


I'm trying to create an association for a beta meat-sale application between one model, Cuts, and the "animal_type" attribute of another model, Animal, such that I could list all the cuts associated with a particular animal_type (or associated with an animal that has that type as an attribute).

In other words, if animal_type is "cow", I should be able to call up a list of all the cuts (ribeye, tenderloin, etc) associated with cows. I'm new to Rails, and this is fairly above my head.

My idea was to create an animal_type column in Cuts and Animals, to associate each cut with a type of animal, so I could do something along the lines of

@cuts = Cut.where(:animal_type => Animal::animal_type[:Cow])

No idea if that works, though, and what else I need to do to make this association possible. Can anybody help point me towards a way of thinking this through? Or does anyone have any good resources I could look at to help me with this specific problem? I've been looking through Rails Guides, and they're helpful, but they don't really give me a way to answer this.


Solution

  • You could have a Cuts model and an Animal model. Cuts could have a string attribute called "name" which would store the cut type such as ribeye, tenderloin etc. Animal could have a string attribute called animal_type. You could then setup a has_many association between Animals and Cuts. Something like this:

    class Animal < ActiveRecord::Base
      attr_accessible :animal_type
      has_many :cuts
    end
    
    class Cuts < ActiveRecord::Base
      attr_accessible :name
      belongs_to :animals
    end
    

    This should be a good start