【问题标题】:Rails method on ActiveRecord::Associations::CollectionProxyActiveRecord::Associations::CollectionProxy 上的 Rails 方法
【发布时间】:2014-01-27 22:56:47
【问题描述】:

我有一个难题。我的控制器中有一个巨大的功能,可以将不同类型的数据负载标准化到一个视图列表中。所以我目前有这样的处理方式:

customer.notes.each do |note|
    to_push = {
      id: note.id,
      title: 'Contact Note',
      type: 'note',
      description: note.notes,
      user: note.user,
      date: note.date,
      action: nil,
      extras: note.customer_interests,
      closed: false,
      colour: '#9b59b6'
    }

    history.push to_push
  end

我想将它从控制器中移到模型中,但我不太确定如何操作。理想情况下,我想要一个像 customer.notes.format_for_timeline 这样的方法,但我不知道如何在类中的 self 方法中迭代这样的结果。

谢谢

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    我知道了。使用self 方法然后all:

    def self.format
      all.each do |item|
        # Manipulate items here
      end
    end
    

    但是,我最终得到了这样的方法:

    def format
      {
        id: id,
        note: 'Contact Note',
        # Etc
      }
    end
    

    然后就用了:

    customer.notes.map {|i| i.format }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-18
      • 2014-04-26
      • 1970-01-01
      • 1970-01-01
      • 2018-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多