Rails - default value in text_field but only for new_record?

jyoseph picture jyoseph · Jan 9, 2011 · Viewed 17.7k times · Source

On a Content model have an attribute named slug. When creating a new record, I want to use a helper to populate this field, but on an existing record I want to use the value from the database.

Currently I have:

<% if @content.new_record? %>
  <%= f.text_field :slug, :value => "#{generate_slug(6)}" %>
<% else %>
  <%= f.text_field :slug %>
<% end %>

But that seems a bit verbose. Is this the best way, or is there no other way? (Rails newb just trying to find the "Rails way" on issues I'm unsure of)


Edit

I should note that the helper is currently in /app/helpers/application_helper.rb Moved to be a private action in the Contents controller. David's answer worked great.

Answer

David Sulc picture David Sulc · Jan 9, 2011

In your controller

@content.slug ||= generate_slug(6)

This will assign a value to the slug attribute if none is present

Then, in your view you can simply use

<%= f.text_field :slug %>