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>
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 %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With