lonC
lonC

Reputation: 89

activerecord - Time format

This has got to be extremely simple but I'm banging my head against the wall trying to find an answer. I want to find the last updated record using the instance method shown below.

class Subject < ActiveRecord::Base
  has_many :assignments, :dependent => :destroy

  def get_last_assignment_date 
    @last_date = self.assignments.select("date_assigned").last
    @last_day = @last_date.wday
  end

Where my assignments model looks like this:

create_table "assignments", :force => true do |t|
t.date     "date_assigned"
<snip>

But Rails returns the following error for get_last_assignment_date:

undefined method `wday' for #<Assignment date_assigned: "2012-08-30">

I need to convert the value returned by active record to a Time format that Ruby can handle but I can't figure out how to do it and it seems to be so easy that no one has even bothered to write how to do it. I would greatly appreciate it if someone could point me in the right direction.

Upvotes: 1

Views: 387

Answers (1)

Mischa
Mischa

Reputation: 43298

This:

self.assignments.select("date_assigned").last

returns an Assigment object, not a Time object.

So, instead of:

@last_day = @last_date.wday

you have to do:

@last_day = @last_date.date_assigned.wday

You may be aware of this, but just in case: select("date_assigned").last doesn't give you the latest date. You have to use order:

self.assignments.order(:date_assigned).last

Of course if the most recently created object is also the one with the latest date_assigned then it doesn't matter.

Upvotes: 1

Related Questions