weotch
weotch

Reputation: 5878

How to get attributes of associated models from within a model in Rails

I want to essentially make an alias of an attribute in a related model within the first model. Here are my models:

class Ingredient < ActiveRecord::Base
    belongs_to :tag
end

class Tag < ActiveRecord::Base
    has_many :ingredients
end

The tags table has a column called "name." I want to be able to call ingredient.name to get ingredient.tag.name. I tried creating getter/setter methods for "name" in Ingredient but I'm not sure how to fetch the "name" attribute of Tag.

Upvotes: 1

Views: 504

Answers (2)

Abdullah Jibaly
Abdullah Jibaly

Reputation: 54790

class Ingredient < ActiveRecord::Base
    belongs_to :tag

    def name
      tag.name
    end
end

Upvotes: 3

Ryan Bigg
Ryan Bigg

Reputation: 107718

A one-liner equal to Abdullah's answer would be to delegate:

delegate :name, :to => :tag

If you care about making things all on one line.

Upvotes: 1

Related Questions