tommyd456
tommyd456

Reputation: 10683

Loop through array in Ruby/Rails

As I'm pretty much a beginner with Rails I wanted to know how best to loop through an array and modify some values. The array is being rendered to a view where the jQuery will receive the data and display it. I want to do the hard work in the Controller (or I might switch to the model at a later date).

The array is called @invoices but in the array is a timestamp which I want to format.

The code to format is:

Time.at(@invoice.date).strftime("%d/%m/%Y")

Could someone show me how to loop through and overwrite the timestamp value

Upvotes: 0

Views: 2276

Answers (4)

Billy Chan
Billy Chan

Reputation: 24815

Actually what you concerned is how to present the data. This is not the logic belongs to controller.

A better way is to do it in model. Suppose you using JSON to render data to jQuery, you just need to add a present method and override as_json

class Invoice < ActiveRecord::Base
  # Add a method to present the original date
  def formatted_date
    Time.at(self.date).strftime("%d/%m/%Y")
  end

  # Include above method in Controller's to_json and remove old :date
  def as_json(options)
    super(method: :formatted_date, except: :date)
  end
end

Then in controller you need to do nothing.

Upvotes: 1

spickermann
spickermann

Reputation: 106882

You should not change your data, if you only want to to display it in a specific format.

Rails allows you to change the format how a Date is rendered in views (specific per locale):

# config/locales/en.yml
en:
  time:
    formats:
      my_format: "%d/%m/%Y"

# in the view
<%= l invoice.date, format: :my_format %>

(see: http://guides.rubyonrails.org/i18n.html#adding-date-time-formats)

Or (if you do not need locale support) you add our own format to the to_formatted_s method:

# in config/initializers/date_formats.rb
Date::DATE_FORMATS[:my_format] = "%d/%m/%Y"
Time::DATE_FORMATS[:my_format] = "%d/%m/%Y"

# in the view
<%= invoice.date.to_s(:my_format) %>

(see: http://api.rubyonrails.org/classes/Time.html#method-i-to_formatted_s)

Upvotes: 0

Vidya
Vidya

Reputation: 30310

I wasn't clear if you are sending just the dates to JQuery. If so, you can do this in your controller:

respond_to do |format|
   format.html { render :json => @invoices.collect {|invoice| invoice.date.strftime("%d/%m/%Y")} }
end

Note the absence of @ before invoice within the block since invoice is the alias for the individual element in the array currently being processed.

If you want the whole invoice, it is only slightly more complicated, and there is a bunch of Ruby cleverness that can minimize the number of lines.

Upvotes: 0

ssantos
ssantos

Reputation: 16526

One possible syntax for a ruby loop would be.-

@invoices.each do |invoice|
    invoice.date = Time.at(invoice.date).strftime("%d/%m/%Y")
end

Upvotes: 2

Related Questions