Rails: Setting a value to input field if variable exists

蹲街弑〆低调 提交于 2019-12-21 19:45:47

问题


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


来源:https://stackoverflow.com/questions/31709477/rails-setting-a-value-to-input-field-if-variable-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!