andy
andy

Reputation: 2409

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.

Thanks

Upvotes: 0

Views: 724

Answers (1)

andy
andy

Reputation: 2409

I found out how. Using a self method then 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 }

Upvotes: 1

Related Questions