简体   繁体   English

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. 我正在使用某些模型,其中许多给定模型的关键属性实际上存储在子模型中。

Example: 例:

class WikiArticle
  has_many :revisions
  has_one :current_revision, :class_name => "Revision", :order => "created_at DESC"
end
class Revision
  has_one :wiki_article
end

The Revision class has a ton of database fields, and the WikiArticle has very few. Revision类具有大量的数据库字段,而WikiArticle却很少。 However, I often have to access a Revision's fields from the context of a WikiArticle. 但是,我经常必须从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

And then on my save, I save @description into a new revision. 然后在保存时,我将@description保存到新修订版中。

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. 这整个事情使我想起了很多attr_accessor,只是似乎我无法让attr_accessor来做我需要的事情。 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? 如何定义attr_submodel_accessor,这样我就可以给出字段名称,并像attr_accessor一样自动创建所有这些方法?

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, eg: 您可以根据需要使用多种方法来执行此操作,例如:

delegate :description, :title, :author, :to => :current_revision

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

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