Ruby on Rails:子模型的attr_accessor [英] Ruby on Rails: attr_accessor for submodels
问题描述
我正在使用某些模型,其中许多给定模型的关键属性实际上存储在子模型中.
I'm working with some models where a lot of a given model's key attributes are actually stored in a submodel.
示例:
class WikiArticle
has_many :revisions
has_one :current_revision, :class_name => "Revision", :order => "created_at DESC"
end
class Revision
has_one :wiki_article
end
Revision类具有大量的数据库字段,而WikiArticle却很少.但是,我经常必须从WikiArticle的上下文中访问修订版的字段.最重要的情况可能是创建文章.我一直在用很多看起来像这样的方法来做到这一点,每个字段一个:
The Revision class has a ton of database fields, and the WikiArticle has very few. However, I often have to access a Revision's fields from the context of a WikiArticle. The most important case of this is probably on creating an article. I've been doing that with lots of methods that look like this, one for each field:
def description
if @description
@description
elsif current_revision
current_revision.description
else
""
end
end
def description=(string)
@description = string
end
然后在保存时,我将@description保存到新修订版中.
And then on my save, I save @description into a new revision.
这整个事情让我想起了很多attr_accessor,只是似乎我无法让attr_accessor来做我需要的事情.如何定义attr_submodel_accessor,以便我可以给出字段名称,并像attr_accessor一样自动创建所有这些方法?
This whole thing reminds me a lot of attr_accessor, only it doesn't seem like I can get attr_accessor to do what I need. How can I define an attr_submodel_accessor such that I could just give field names and have it automatically create all those methods the way attr_accessor does?
推荐答案
术语子模型"使我失望,因为它是非标准术语,但我认为您正在寻找的是
The term "submodel" threw me off because it's nonstandard terminology, but I think what you're looking for is delegate. Basically it lets you delegate certain method calls to a property or instance method of an object.
在这种情况下,您将执行以下操作:
In this case you would do something like this:
class WikiArticle
has_many :revisions
has_one :current_revision, :class_name => "Revision", :order => "created_at DESC"
delegate :description, :to => :current_revision
end
您可以根据需要使用多种方法来执行此操作,例如:
You can do this for as many methods as you want, e.g.:
delegate :description, :title, :author, :to => :current_revision
这篇关于Ruby on Rails:子模型的attr_accessor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!