【问题标题】:Using after_create使用 after_create
【发布时间】:2011-02-04 20:09:09
【问题描述】:

我有一个模型,类别。我想在创建类别时创建一个新的默认 sub_category 。但我不知道该怎么做。这是我所拥有的。

class Category < ActiveRecord::Base
    attr_accessible :title, :position

    has_many :sub_categories

    after_create :make_default_sub

    def make_default_sub
      #Sub_Categories.new( :title=>' ');
    end
end

【问题讨论】:

    标签: ruby-on-rails-3 active-relation


    【解决方案1】:

    为什么不使用ancestry gem?将来如果您有更多的子类别,管理它们会更容易。

    例如你的情况:

    class Category < ActiveRecord::Base
        attr_accessible :title, :position
    
        has_ancestry
    
        after_create :create_default_subcategory
    
        def make_default_sub
          children = self.children.new
          children.title = ''
          children.position = 1 # or autogenerated
          children.save!
        end
    end
    

    但是你能解释一下,为什么你需要这么奇怪的默认行为?

    谢谢

    【讨论】:

    • 我所有的广告都属于子类别而不是类别
    • 我建议你直接阅读github上的手册。这很容易......真的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多