在rails中创建组合对象的最佳方法是什么

时间:2013-04-14 22:18:53

标签: ruby-on-rails ruby activerecord

我想用这种行为创建一个组合对象:

page = MinimalistCms::Page.create
page.test #return undefined method
page.parts.create!(title: 'test', body: 'test')
page.test #return 'test'
page.test = 'a body'
page.test #return 'a body'

为此,我创建了这个类:

module PartComposition
  def self.included(model_class)
    model_class.class_eval do
      has_many :parts, class_name: 'PagePart'
    end
  end

  def method_missing(name, *args)
    title = name.to_s.downcase.underscore
    if title.end_with?('=')
      return update_part(title, args.first)
    else
      part = find_part(title)
      if part
        return part.body
      else
        super(name, *args)
      end
    end
  end

  private
  def update_part(title, attribute)
    part = find_part(title.chop)
    return part.update_attribute(:body, attribute)
  end

  def find_part(title)
    parts.with_globalize(title: title).first
  end
end

它有效,但当我这样做page.body = 'test'时,它会自动保存记录。我不确定这是最好的方式。

第一次,page.test应返回未定义的方法。要创建零件,应创建新的虚拟属性。该属性应该与普通属性完全相同。

你的想法吗?

1 个答案:

答案 0 :(得分:0)

如果您不想保存该部件,请执行part.body = attribute而不是part.update_attribute。然后,您可以拥有一个包含未保存部分列表的实例变量dirty_parts,在发出savesave!时,您可以保存部分并调用super,或者放置零件关系中autosave

无论如何,我喜欢它现在的样子。