简体   繁体   English

如何从Rails中的模型中获取关联模型的属性

[英]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. 我希望能够调用ingredient.name来获取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. 我尝试在Ingredient中为“name”创建getter / setter方法,但我不知道如何获取Tag的“name”属性。

class Ingredient < ActiveRecord::Base
    belongs_to :tag

    def name
      tag.name
    end
end

A one-liner equal to Abdullah's answer would be to delegate : 一个等于阿卜杜拉答案的单行将delegate

delegate :name, :to => :tag

If you care about making things all on one line. 如果你关心在一条线上做所有事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM