0

I want to change a string returned from the following format to a date that shows how many months days since the last order was placed from a customer, I have the following code on the page to get the result -

<% @lastorder = Order.select("DateCreated").where("customer_id == ?", customer.id).order("Datecreated desc").find(:all, :limit => 1) %>

but this then returns the following format -

 [#<Order DateCreated: "2013-01-09 00:00:00">]

There is probably a better way to do this but I am unaware of it at the moment.

1 Answer 1

1

I would rewrite your query like that :

@last_order = Order
  .where(customer_id: customer.id) # No need to use prepared statement here
  .order('DateCreated DESC')
  .pluck('DateCreated')            # Directly select 1 column
  .first()                         # Only select the first record

If you want to display the time distance in words, you should use the rails helper : distance_of_time_in_words_to_now(@last_order)

Info: Just discover than distance_of_time_in_words_to_now is an alias of time_ago_in_words, shorter.

Sign up to request clarification or add additional context in comments.

4 Comments

There is one hiccup however - <%= distance_of_time_in_words_to_now(@last_order) %> throws an error - can't convert nil into an exact number
That's when your request returns no result. You need to check whether a result is returned or not before (the customer should have no order)
Thanks, used - <% if @last_order.present? %><%= distance_of_time_in_words_to_now(@last_order) %><% end %>
You can do <%= distance_of_time_in_words_to_now(@last_order) if @last_order %> or <%= distance_of_time_in_words_to_now(@last_order) unless @last_order.nil? %>

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.