我对 RoR 比较陌生。我在haml中得到了以下来源
= form.text_field :country, 'Country'
= form.text_field :state, 'State', :placeholder => 'optional'
但是 :state 字段并不是完全可选的,只有当用户是非美国用户时才可选,如果他/她的国家=='美国',则该字段必须成为必需的。
最佳答案
何不努力,
在你的情况下,
HAML 是基于缩进的,解析器可能很棘手。您不需要在 Haml 中使用“-end”。改用缩进。在 Haml 中,每当在 Ruby 求值命令之后增加缩进时,就会开始一个块。当缩进减少时结束。示例 if else 块如下。
- if country != 'USA' # change country variable to your country value variable
= form.text_field :state, 'State', :placeholder => 'optional'
- else
= form.text_field :state, 'State', :placeholder => 'Mandatory'
如果您只想使用
IF
健康)状况,- if country != 'USA' # change country variable to your country value variable
= form.text_field :state, 'State', :placeholder => 'optional'
在普通的 ruby 形式代码中,
<% if @country == 'USA' %> # change @country variable to your country value variable
<%= form.text_field :state, 'State', :placeholder => 'Mandatory' %>
<% else %>
<%= form.text_field :state, 'State', :placeholder => 'optional' %>
<% end %>
以上只是获得想法的一个例子..因为我不知道存储在哪个变量中的国家/地区值。
关于ruby-on-rails - rails : Form with conditional required field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15246465/