Updating last_viewed field rails
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.
精彩评论