【问题标题】:Custom setter for foreign key attribute for Mongoid using Rails使用 Rails 的 Mongoid 外键属性的自定义设置器
【发布时间】:2011-10-13 23:02:18
【问题描述】:

在我的 rails 应用程序中,有一个像这样的树状模型:

class File
  belongs_to :parent, :foreign_key => "parent_id", :class_name => "File"
end

我想为父 setter 的行为添加功能。所以像这样的东西(除了它不起作用)?

def parent=(new_parent)
  super(new_parent)
  # Additional stuff I want to do here
end

我需要默认行为仍然存在,因为我认为它管理关系,但我需要知道父级何时更改,以便我可以执行一些额外的任务。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 mongodb mongoid


    【解决方案1】:

    我目前的解决方法是这样的:

    class File   
      belongs_to :parent, :foreign_key => "parent_id", :class_name => "File"   
      before_save :check_parent
    
      def check_parent
        if self.parent_id_changed?
          # Additional stuff I want to do here
        end   end end
    

    唯一的缺点是你必须保存它才能启动。理想情况下,我希望它在 parent_id 更改后立即启动。否则,尽管我愿意接受更好的解决方案,但这工作得很好。

    【讨论】:

      猜你喜欢
      • 2011-10-12
      • 2013-01-25
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 2012-07-02
      相关资源
      最近更新 更多