Spencer R
Spencer R

Reputation: 1158

Creating ActiveRecord Model Attribute for use in View

I can't believe I even have to ask this question, but it's been "one of those days" and I can't think straight at all.

I'm creating a simple Rails app using data in a MySQL database. In one of the tables, there's a column for a creation timestamp (creation_ts). What I'd like to do is create a model attribute that becomes a part of each model object. In this case, if a record has a creation timestamp that's older than a month, I want it to have a "late" attribute set as true (false if it's not). Then I could later use that in the view when dynamically setting HTML element attributes.

Again, I should know this (in fact, I've done this before) I'm just drawing a complete blank.

Upvotes: 1

Views: 184

Answers (1)

ipd
ipd

Reputation: 5714

Rails 3 uses 'created_at' to store the date of the first save. In your model, say Model.rb, you could add a late accessor defined as follows:

def late?
    created_at > 1.month.ago
end

Which will return true or false.

Then in your views you could do something like

<% if @model.late? %>
  <%= @model.something_to_show %>
<% end %>

ian.

Upvotes: 2

Related Questions