Rails:如果变量存在,则将值设置为输入字段 [英] Rails: Setting a value to input field if variable exists

查看:104
本文介绍了Rails:如果变量存在,则将值设置为输入字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将ID传递给控制器​​中的新操作时,为两个文本字段输入设置一个值。当前代码有效,但是我想知道代码是否可以缩短。

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.

当前代码

视图

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

我尝试删除if-else部分以使代码更短

I tried removing the if-else part to make the code shorter

短代码

查看

<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">

而第二个输入项消失。

悬挂式价值标签可以吗?我检查了html,如果我单击以html格式编辑,悬挂值标签将解析为value =

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?

推荐答案

具有HTML属性,只是 value 很好,在HTML5中。另外,根据您的 html.erb 原始 HTML源代码可能读为 value =''。 c $ c>代码。

我想您正在使用Chrome或Firefox的开发人员工具,该工具会尝试纠正并为您设置格式奇怪的HTML,并且可能会显示它没有空的 =''

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 =''.

然后,这个问题:

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

运算符优先级。您的 if 适用于整个语句。

尝试:

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

或:

<%= f.text_field :debtor_id, class: "form-control", value: @debtor.try!(:id) %>

这篇关于Rails:如果变量存在,则将值设置为输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆