Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - set default value for form text_field with current_user

I'm trying to default my contact form email field to the current_user.email value. If there's no current_user, then a simple input field should show. I tried the below which works, but if there's no current_user, the the textfield doesn't show.

<div class="form-group">
  <label>Email</label> 
  <%= f.text_field :email, required: true, class: 'form-control', value:current_user.email if current_user  %>
</div>
like image 665
user1322092 Avatar asked Mar 18 '14 00:03

user1322092


1 Answers

Its not showing because the if statement applies to the whole text-field, not just the value attribute. This will work:

<% if current_user %>
    <%= f.text_field :email, required: true, class: 'form-control', value:current_user.email  %>
<% else %>
    <%= f.text_field :email, required: true, class: 'form-control'%>
<% end %>

However, if you are using devise, it comoes with a helper method that is generally better to user than current_user. I think your code should be this:

<% if user_signed_in? %>
    <%= f.text_field :email, required: true, class: 'form-control', value:current_user.email %>
<% else %>
    <%= f.text_field :email, required: true, class: 'form-control'%>
<% end %>
like image 110
Philip7899 Avatar answered Sep 23 '22 18:09

Philip7899