在我的应用程序中,我有一个 Widget
模型,一个 Feature
带 的模型has_many 通过 协会来自 WidgetFeature
table 。
根据要求,当我发送 WidgetFeature 对象时,对于关联的给定功能,我还应该将 feature_name 附加到它。
有两种方法:
widget_feature_object[:feature_name] = feature_name_value
然后我可以通过
widget_feature_object[:feature_name]
在我的 Controller 或 View 中访问它因为一个对象有 (key, value) 对,所以我也可以添加另一个。2 .制作
feature_name
虚拟属性在 WidgetFeature
模型,然后为其创建 getter 和 setter 方法。据我所知,当您想要创建与模型中实际存在的字段不同的 View 时,您应该使用虚拟属性(例如,全名 = 名字 + 姓氏)。
同样的东西也适合这里吗?
还有 ,Rails 是否对对象进行了一些缓存,当您使用虚拟属性而不是我使用第一种方法时,这可能会很有用?
每种方法的优缺点是什么,哪种方法最适合我的要求?
非常感谢。
最佳答案
我会提出另一种方法:使用 delegate
( documentation )。
在 WidgetFeature
我会写:
class WidgetFeature
belongs_to :feature
delegate :name, :to => :feature, :prefix => true
end
然后你就可以写了
f = WidgetFeature.first
f.feature_name #will return f.feature.name
希望这可以帮助。
关于ruby-on-rails - 何时在 Rails 3 中使用虚拟属性或以散列形式传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6469538/