Rails: setting value for input field if variable exists
I am trying to set a value for two inputs of a textbox when an ID is passed to a new activity in a controller. The current code works, but I'm wondering if the code can be shortened.
Current code
View
<div class="custom-input">
<% if @debtor %>
<input type="text" name="debtor_name" class="form-control" id="debtor-search-form" value='<%= @debtor.name %>'>
<% else %>
<input type="text" name="debtor_name" class="form-control" id="debtor-search-form">
<% end %>
</div>
<% if @debtor %>
<%= f.text_field :debtor_id, class: "form-control", value: @debtor.id %>
<% else %>
<%= f.text_field :debtor_id, class: "form-control" %>
<% end %>
I tried to remove the if-else part to make the code shorter
Shorter code
View
<div class="custom-input">
<input type="text" name="debtor_name" class="form-control" id="debtor-search-form" value='<%= @debtor.name if @debtor %>'>
</div>
<%= f.text_field :debtor_id, class: "form-control", value: @debtor.id if @debtor %>
When the debtor is not passed, the shorthand code causes the first input to have a "hanging" value tag (i.e. it just shows the value, followed by an equal sign)
<input type="text" name="debtor_name" class="form-control ui-autocomplete-input" id="debtor-search-form" value autocomplete="off">
while the second entry disappears.
Is the hanging value tag ok? I checked the html and the value tag "hangs" resolves value = "if I click" edit as html "
Is there a way to shorten the code or should I just stick with it?
source to share
Having an HTML attribute as soon value
as is ok in HTML5. Also, the original HTML source probably reads like value=''
judging by your code html.erb
.
I am assuming that you are using Chrome or Firefox developer tools that will try to fix and format the odd HTML for you, and will probably display it without blank =''
.
Then the problem with this:
<%= f.text_field :debtor_id, class: "form-control", value: @debtor.id if @debtor %>
Is the operator's priority. Yours if
applies to the entire application.
Try:
<%= f.text_field :debtor_id, class: "form-control", value: (@debtor.id if @debtor) %>
Or:
<%= f.text_field :debtor_id, class: "form-control", value: @debtor.try!(:id) %>
source to share