How do I say if value exists display value otherwise leave well enough alone with simple_form?

By : Lenocam
Source: Stackoverflow.com
Question!

I'm using simple_form and I only want the value: @image.start_at.strftime("%m/%d/%Y %I:%M %p") %> to execute if @image.start_at has a value.

<div class="input-group date" id="datetimepicker">
    <%= f.text_field :start_at, class: 'form-control', value: @image.start_at.strftime("%m/%d/%Y %I:%M %p") %>
    <span class="input-group-addon">
      <span class="glyphicon glyphicon-calendar"></span>
    </span>
</div>

For example, this is from my image create/update _form and this works seemingly exactly how I want it to if I already have an image that has a start_at value. However, when I am creating a new image and there is no start_at value yet how can I say don't try to put this value in the input? I'm not interested in having a default value.

By : Lenocam


Answers

can you do something like this?

<div class="input-group date" id="datetimepicker">
    <%= f.text_field :start_at, class: 'form-control', value: @image.start_at.strftime("%m/%d/%Y %I:%M %p") if @image.start_at.present? %>
    <span class="input-group-addon">
      <span class="glyphicon glyphicon-calendar"></span>
    </span>
</div>

which puts an if statement inline with value

By : Eric


<%= f.text_field :start_at, class: 'form-control', value: @image.start_at? ? @image.start_at.strftime("%m/%d/%Y %I:%M %p") : nil %>

based on @luissimo 's answer

By : Lenocam


Check for blank and assign a value appropriately:

<%  @image.start_at.blank? ? starts_at = nil : starts_at = @image.start_at.strftime("%m/%d/%Y %I:%M %p")  %>
<div class="input-group date" id="datetimepicker">
    <%= f.text_field :start_at, class: 'form-control', value: starts_at %>
    <span class="input-group-addon">
      <span class="glyphicon glyphicon-calendar"></span>
    </span>
</div>
By : bkunzi01


This video can help you solving your question :)
By: admin