Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Setting a value to input field if variable exists

I'm trying to set a value to two text field inputs when an id is passed to the new action in the 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 removing 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 no debtor is passed, the shortened code results to the first input having a "hanging" value tag (i.e. it just shows value. no equal sign after it)

<input type="text" name="debtor_name" class="form-control ui-autocomplete-input" id="debtor-search-form" value autocomplete="off">

while the second input disappears.

Is a "hanging" value tag ok? I inspected the html and the "hanging" value tag resolves to value="" if i click 'edit as html'

Is there a way to shorten the code or should i just stick with it?

like image 308
osse Avatar asked Jan 07 '23 21:01

osse


2 Answers

Having an HTML attribute as just value is fine, in HTML5. Also, the raw HTML source code probably reads as value='', judging by your html.erb code.
I guess that you're using Chrome's or Firefox's developer tools, that will try to correct and format odd looking HTML for you, and will probably display it without the empty =''.

Then, the problem with this:

<%= f.text_field :debtor_id, class: "form-control", value: @debtor.id if @debtor %>

Is operator precedence. Your if applies to the whole statement.
Try with:

<%= 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) %>
like image 168
tompave Avatar answered Jan 27 '23 18:01

tompave


The hanging value tag doesn't make a difference. As you saw yourself, it's the same as value="", which is the "default" value. It is also completely valid HTML5.

like image 28
Ilya O. Avatar answered Jan 27 '23 18:01

Ilya O.