我正在尝试将其他字段“部门”添加到现有的设计注册模板中。我正在尝试实现一个下拉列表,其中包含dept1,dept2 ....,not_listed等部门列表。当选择not_listed时,我想显示文本框,用户可以在其中输入自定义部门并将部门的值存储在数据库中而不是未列出。
这是代码。
<div class="border-form-div">
<h3 class="text-center">Create a new account</h3>
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<div class="form-group">
<%= f.email_field :email, :autofocus => true, :placeholder => "Email address", class: "form-control", required: false %>
</div>
<div class="form-group">
<%= f.password_field :password, :placeholder => "Password", class: "form-control", required: false %>
</div>
<div class="form-group">
<%= f.password_field :password_confirmation, :placeholder => "Confirm password", class: "form-control", required: false %>
</div>
<div class="form-group">
<%= f.select :department, options_for_select(["dept1", "dept2", "dept3", "dept4", "Not Listed"]), class: "form-control", html: { id: "dept-id"} %>
</div>
<div>
<ul><%= f.text_field :department, :placeholder => "enter your department", html: {id: "not_listed_1"} %></ul>
</div>
<script>
$(document).ready(function(){
$('#dept-id').change(function() {
var selected = $(this).val();
if(selected == 'Not Listed'){
$('#not_listed_1').show();
}
else{
$('#not_listed_1').hide();
}
});
});
</script>
<br>
<div class="text-center">
<div class="form-group">
<%= f.submit "Sign up", :class => "btn btn-primary", :id => "page[sign_up]" %>
<%= link_to "Cancel", new_user_session_path, class: "btn btn-default", :id => "page[cancel]" %>
</div>
</div>
我对jquery并不擅长。有人可以指出我哪里出错了吗?
答案 0 :(得分:0)
这是适用于我的解决方案,我测试了它。您只需要添加和修改几行代码,它就会对您有用。
首先,我添加了字段部门来设计模型:rails g migration User department:string
和run db:migrate
。
然后我制作了自定义注册控制器(扩展了Devise&#39):
# app/controllers/registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
private
def sign_up_params
params.require(:user).permit(:department, :email, :password, :password_confirmation)
end
def account_update_params
params.require(:user).permit(:department, :email, :password, :password_confirmation, :current_password)
end
end
更新
我的路线文件现在看起来像这样:
devise_for :users, :controllers => { registrations: 'registrations' }
然后我生成了Devise视图:rails generate devise:views
我从以下位置打开了Devise的视图注册文件: app / views / devise / registrations / new.html.erb 以添加新视图表单字段:
<div class="form-group">
<%= f.select :department, options_for_select(["dept1", "dept2", "dept3", "dept4", "Not Listed"], :selected => f.object.department), class: "form-control" %>
</div>
<div id="show_dep" style="display: none">
Please enter your department: <br />
<%= f.text_field :department, :placeholder => "enter your department", html: {id: "#show_dep"} %>
</div>
最后一段代码是jQuery :(你可以添加到application.js)
jQuery(function () {
$("#user_department").change(function () {
if ($(this).val() == "Not Listed") {
$("#show_dep").show();
} else {
$("#show_dep").hide();
}
});
});
我检查了rails控制台,(User.last
),并且:部门字段填充了来自用户输入的数据。
我希望它有所帮助,
干杯!