简体   繁体   English

ActiveRecord :: Associations :: CollectionProxy上的Rails方法

[英]Rails method on ActiveRecord::Associations::CollectionProxy

I have a dilema. 我有一个难题。 There's a huge function in my controller to standardise loads of different types of data into one list for the view. 我的控制器中有一个强大的功能,可以将不同类型的数据加载标准化到一个视图列表中。 So I have this kind of way of handling it at the moment: 因此,目前我有这种处理方式:

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

I want to move that out of the controller into the model but I'm not too sure how. 我想将其从控制器中移到模型中,但是我不太确定该怎么做。 I ideally want a method like customer.notes.format_for_timeline but I can't figure out how to iterate over results like that in a self method within the class. 理想情况下,我希望使用诸如customer.notes.format_for_timeline类的方法,但我无法弄清楚如何在类中的self方法中对结果进行迭代。

Thanks 谢谢

I found out how. 我发现了。 Using a self method then all : 使用self方法则all

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

However, I ended up having a method like this: 但是,我最终有了这样的方法:

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

Then just used: 然后就用了:

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

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

相关问题 Rails“ActiveRecord_Associations_CollectionProxy的未定义方法” - Rails “undefined method for ActiveRecord_Associations_CollectionProxy” ActiveRecord_Associations_CollectionProxy的未定义方法[rails] - undefined method for ActiveRecord_Associations_CollectionProxy [rails] # <ActiveRecord::Associations::CollectionProxy []> 在Rails中 - #<ActiveRecord::Associations::CollectionProxy []> in Rails Rails,ActiveRecord_Associations_CollectionProxy调用ActiveRecord方法的方式 - Rails, The way for ActiveRecord_Associations_CollectionProxy to call method of ActiveRecord Rails 3 HABTM产生ActiveRecord :: Associations :: CollectionProxy对象 - Rails 3 HABTM yields ActiveRecord::Associations::CollectionProxy objects 在Capybara中伪装ActiveRecord :: Associations :: CollectionProxy与Mocha(Rails) - Faking ActiveRecord::Associations::CollectionProxy with Mocha in Capybara (Rails) Rails循环通过ActiveRecord :: Associations:CollectionProxy - Rails loop through ActiveRecord::Associations:CollectionProxy 表导轨中ActiveRecord :: Associations :: CollectionProxy的排序顺序 - Sort order for ActiveRecord::Associations::CollectionProxy in table rails ActiveRecord_Associations_CollectionProxy上的重写方法 - Override method on ActiveRecord_Associations_CollectionProxy #的未定义方法“ url” <ActiveRecord::Associations::CollectionProxy []> - undefined method `url' for #<ActiveRecord::Associations::CollectionProxy []>
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM