开发者

Updating last_viewed field rails

开发者 https://www.devze.com 2023-02-15 12:09 出处:网络
I have a field that stores the last_viewed time. Is the best way to update this field by doing: @course_enrollment.last_viewed = Time.now

I have a field that stores the last_viewed time. Is the best way to update this field by doing:

@course_enrollment.last_viewed = Time.now
@course_enrollment.save()

This field is a datetime as the 开发者_如何学运维database type and a timestamp as the rails migration type.


If you are calling this in a controller I would probably do something like this:

class CourseEnrollment < AR::Base
  # ...

  def mark_as_viewed
    update_attributes(:last_viewed => Time.now)
  end
end

# in controller
@course_enrollment.mark_as_viewed

That way you can easily unit test it and remove a little logic from the controller.


It is litte less code to do it like this:

@course_enrollment.update_attributes(:last_viewed => Time.now)


The correct way to do this would be to touch the record:

@course_enrollment.touch(:last_viewed)

This would update the last_viewed and updated_at columns to the current time.

0

精彩评论

暂无评论...
验证码 换一张
取 消