Rails: Setting a value to input field if variable

2019-05-10 11:40发布

问题:

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?

回答1:

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) %>


回答2:

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.



回答3:

You can use try try object

<div class="custom-input">      
  <input type="text" name="debtor_name" class="form-control" id="debtor-search-form" value='<%= @debtor.try(:name) %>'>
</div>
<%= f.text_field :debtor_id, class: "form-control", value: @debtor.try(:id) %>