【问题标题】:Rails Dependent Form FieldRails 相关表单字段
【发布时间】:2017-07-13 16:51:05
【问题描述】:

我正在使用dependent fields rails gemthis video tutorial 尝试在我的用户注册表单中实现一个依赖字段。我的注册表单有一个字段,用户可以在其中选择他们的角色(使用枚举实现)。我希望默认情况下隐藏大学字段,并且仅在用户选择“员工”作为其角色时才显示。当前的行为是所有表单字段在加载时都是可见的。我究竟做错了什么?对新手的任何帮助将不胜感激!我已阅读其他 SO 问题,但似乎无法使其正常工作。

这是我的表格:

<% provide(:title, 'Sign up') %>
<h1>Sign up</h1>

<div class="row">
  <div class="col-md-6 col-md-offset-3">
    <%= form_for(@user) do |f| %>
      <%= render 'shared/error_messages', object: f.object %>
      <%= f.label :name %>
      <%= f.text_field :name, class: 'form-control' %>

      <%= f.label :email %>
      <%= f.email_field :email, class: 'form-control' %>

      <%= f.label :role %>
      <%= f.select(:role, User.roles.keys.map {|role| [role.titleize,role]}, :include_blank => "Please Select")  %>

      <%= content_tag :div, class: 'js-dependent-fields', data: { 'data-select-id': 'user_role', 'data-option-value': 'staff'} do %>
      <%= f.label :university_id%>
      <%= collection_select( :user, :university_id, University.all, :id, :name, prompt: true) %>
      <% end %>

      <%= f.label :password %>
      <%= f.password_field :password, class: 'form-control' %>

      <%= f.label :password_confirmation, "Confirmation" %>
      <%= f.password_field :password_confirmation, class: 'form-control' %>

      <%= f.submit "Create my account", class: "btn btn-primary" %>
    <% end %>
  </div>
</div>

这是我的 application.js 的下半部分:

//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require bootstrap
//= require turbolinks
//= require underscore
//= require dependent-fields
//= require_tree .

 $(document).ready(function() {
     DependentFields.bind()
 });

【问题讨论】:

  • 您的浏览器控制台是否显示任何 JS 错误?你在$(document).ready(...)上给DependentFields.bind()打电话了吗?
  • 我的浏览器控制台什么也没显示。我将我的 application.js 添加到原始问题中。
  • 我在 vendor/assets/javascripts 中也有 underscore.js

标签: ruby-on-rails forms


【解决方案1】:

可能不是原因,但我相信您的 data 属性附加了一个额外的“data-”块:

<%= content_tag :div, class: 'js-dependent-fields', data: { 'data-select-id': 'user_role', 'data-option-value': 'staff'} do %>
  vv
<%= content_tag :div, class: 'js-dependent-fields', data: { 'select-id': 'user_role', 'option-value': 'staff'} do %>

【讨论】:

  • 这修复了它!谢谢安德鲁!
  • 天哪!没问题。投票给我的答案:)
猜你喜欢
  • 1970-01-01
  • 2020-01-01
  • 1970-01-01
  • 2016-05-23
  • 2015-12-15
  • 1970-01-01
  • 2016-03-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多