Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - default value in text_field but only for new_record?

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.

like image 253
jyoseph Avatar asked Jan 09 '11 04:01

jyoseph


1 Answers

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 %>
like image 152
David Sulc Avatar answered Oct 19 '22 23:10

David Sulc