Rails - set default value for form text_field with current_user

I am trying to set my mailbox by default in the current_user.email field. If there is no current_user, then a simple input field should be displayed. I tried the following, which works, but if there is no current_user, the text box is not displayed.

<div class="form-group">
  <label>Email</label> 
  <%= f.text_field :email, required: true, class: 'form-control', value:current_user.email if current_user  %>
</div>
+4
source share
2 answers

Not displayed because the if statement applies to the entire 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 use devise, it combines with a helper method, which is usually better for the user than current_user. I think your code should be as follows:

<% 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 %>
+6

http://apidock.com/rails/Object/try

<%= f.text_field :email, required: true, class: 'form-control', value: current_user.try(:email)  %>
+3

Source: https://habr.com/ru/post/1532227/


All Articles