Ruby on rails RubyonRails:使用引导模式生成注册表的最佳方法是什么?
我正在尝试使用引导模式弹出窗口为RubyonRails应用程序创建一个注册表单。我自己从头开始硬编码表单(没有使用SimpleForm或Desive)。单击“提交”时,我似乎无法传递数据 以下是用户_controller.rb:Ruby on rails RubyonRails:使用引导模式生成注册表的最佳方法是什么?,ruby-on-rails,forms,twitter-bootstrap,modal-dialog,registration,Ruby On Rails,Forms,Twitter Bootstrap,Modal Dialog,Registration,我正在尝试使用引导模式弹出窗口为RubyonRails应用程序创建一个注册表单。我自己从头开始硬编码表单(没有使用SimpleForm或Desive)。单击“提交”时,我似乎无法传递数据 以下是用户_controller.rb: class UsersController < ApplicationController #before_action :confirm_logged_in respond_to :html, :js def index @users = User.
class UsersController < ApplicationController
#before_action :confirm_logged_in
respond_to :html, :js
def index
@users = User.all.sorted
end
def show
@user = User.find(params[:id])
end
def new
@user = User.new
end
def create
@user = User.new(user_params)
respond_to do |format|
format.html { redirect_back }
format.js
end
if @user.save
flash[:success] = 'Welcome, #{@user.first_name}!'
else
render('new')
end
end
def edit
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
if @user.update_attributes(user_params)
flash[:success] = 'You have been updated.'
redirect_to(:action => 'show')
else
render('edit')
end
end
def delete
@user = User.find(params[:id])
end
def destroy
@user = User.find(params[:id]).destroy
flash[:notice] = '#{@user.first_name} #{@user.last_name} has been deleted.'
redirect_to ('home')
end
private
def user_params
params.require(:user).permit(:first_name, :last_name, :email, :password, :confirm_password, :avatar)
end
end
以下是我的user.rb模型:
class User < ActiveRecord::Base
has_secure_password
before_save { self.email = email.downcase }
validates :first_name, :presence => true,
:length => { :maximum => 25 }
validates :last_name, :presence => true,
:length => { :maximum => 50 }
VALID_EMAIL_REGEX = /\A[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}\Z/i
validates :email, :presence => true,
:uniqueness => { case_sensitive: false},
:length => { :maximum => 100 },
:format => { with: VALID_EMAIL_REGEX },
:confirmation => true
validates :password, :presence => true,
:length => { :within => 6..20 }
validates_confirmation_of :password
#mount_uploader :picture, PictureUploader
#validate :picture_size
validates :avatar, :attachment_presence => true
validates_with AttachmentPresenceValidator, :attributes => :avatar
validates_with AttachmentSizeValidator, :attributes => :avatar, :less_than => 1.megabytes
scope :sorted, lambda { order("last_name ASC, first_name ASC") }
def name
"#{first_name} #{last_name}"
end
private
def picture_size
if picture.size > 5.megabytes
errors.add(:picture, " must be less than 5MB")
end
end
end
class用户true,
:length=>{:max=>25}
验证:last_name,:presence=>true,
:length=>{:max=>50}
有效的电子邮件\u REGEX=/\A[A-z0-9.\uz0%+-]+@[A-z0-9.-]+\[A-z]{2,4}\z/i
验证:email,:presence=>true,
:university=>{区分大小写:false},
:length=>{:max=>100},
:format=>{with:VALID_EMAIL_REGEX},
:确认=>true
验证:password,:presence=>true,
:length=>{:within=>6..20}
验证密码的确认
#挂载上传器:图片,图片上传器
#验证:图片大小
验证:化身,:附件\u状态=>true
使用AttachmentPresenceValidator验证_,:attributes=>:avatar
使用AttachmentSizeValidator验证_,:attributes=>:avatar,:小于=>1.MB
范围:排序,lambda{顺序(“姓氏ASC,姓氏ASC”)}
定义名称
“#{姓}#{姓}”
结束
私有的
def图片大小
如果picture.size>5.MB
错误。添加(:图片,“必须小于5MB”)
结束
结束
结束
这就是如何通过ajax加载表单并将其注入引导模式的方法。请注意,这是基于一个-你将需要适应自己的应用程序它
1.设置特定于页面的javascript
更改视图/application/layout.html.erb中的body标记
<body data-controller="<%= controller_name %>" data-action="<%= action_name %>">
这让我们只需在主页上显示模式。如果您的模态不是“飞溅”,请随意跳过此步骤
在我的示例中,我将pages\home
作为根路径
2.创建一个模态模板
在视图/layouts/_modal.html.erb
中创建通用模式模板
<div class="modal fade" id="modal-template" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="exampleModalLabel">Generic Modal Title</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- ... -->
</div> <!-- /container -->
<%= render partial: 'layouts/modal' %>
</body>
</html>
<%= form_for(@user) do |f| %>
<% if @user.errors.any? %>
<div id="form-errors">
<h2><%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:</h2>
<ul>
<% @user.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="form-inputs">
<div class="form-group has-success has-feedback">
<%= f.label :first_name, class: "sr-only" %>
<%= f.text_field(:first_name, class: "form-control", placeholder: "First Name") %>
<span class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"></span>
</div>
<div class="form-group has-success has-feedback">
<%= f.label :last_name, class: "sr-only" %>
<%= f.text_field(:last_name, class: "form-control", placeholder: "Last Name") %>
<span class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"></span>
</div>
<div class="form-group has-success has-feedback">
<%= f.label :email, class: "sr-only" %>
<%= f.text_field(:email, class: "form-control", placeholder: "Email") %>
<span class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"></span>
</div>
<div class="form-group has-success has-feedback">
<%= f.label :password, class: "sr-only" %>
<%= f.password_field(:password, type: "password", class: "form-control", placeholder: "Password") %>
<span class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"></span>
</div>
<div class="form-group has-success has-feedback">
<%= f.label :confirm_password, class: "sr-only" %>
<%= f.password_field(:confirm_password, type: "password", class: "form-control", placeholder: "Confirm Password") %>
<span class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"></span>
</div>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
<h1>New User</h1>
<%= render 'form' %>
<%= link_to 'Back', users_path %>
3.创建注册表。
首先创建一个用户表单部分视图/users/\u form.html.erb
<div class="modal fade" id="modal-template" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="exampleModalLabel">Generic Modal Title</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- ... -->
</div> <!-- /container -->
<%= render partial: 'layouts/modal' %>
</body>
</html>
<%= form_for(@user) do |f| %>
<% if @user.errors.any? %>
<div id="form-errors">
<h2><%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:</h2>
<ul>
<% @user.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="form-inputs">
<div class="form-group has-success has-feedback">
<%= f.label :first_name, class: "sr-only" %>
<%= f.text_field(:first_name, class: "form-control", placeholder: "First Name") %>
<span class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"></span>
</div>
<div class="form-group has-success has-feedback">
<%= f.label :last_name, class: "sr-only" %>
<%= f.text_field(:last_name, class: "form-control", placeholder: "Last Name") %>
<span class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"></span>
</div>
<div class="form-group has-success has-feedback">
<%= f.label :email, class: "sr-only" %>
<%= f.text_field(:email, class: "form-control", placeholder: "Email") %>
<span class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"></span>
</div>
<div class="form-group has-success has-feedback">
<%= f.label :password, class: "sr-only" %>
<%= f.password_field(:password, type: "password", class: "form-control", placeholder: "Password") %>
<span class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"></span>
</div>
<div class="form-group has-success has-feedback">
<%= f.label :confirm_password, class: "sr-only" %>
<%= f.password_field(:confirm_password, type: "password", class: "form-control", placeholder: "Confirm Password") %>
<span class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"></span>
</div>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
<h1>New User</h1>
<%= render 'form' %>
<%= link_to 'Back', users_path %>
4.用Ajax加载表单。
这看起来很复杂,但实际上并不复杂。我们复制添加到页面中的模式模板,并从使用ajax加载的表单中注入组件
$(document).ready(function(){
// Only fire this on the home page.
// Replace this with a regular click handler if you do not want a "splash"
$(document).on('pages:home:loaded', function(){
// Load the page content from "/users/new"
var promise = $.get("/users/new");
// When the ajax request has finished
promise.success(function(data){
var $frag = document.createDocumentFragment(), // Good for performance
$modal = $($('#modal-template')[0].outerHTML, $frag),
$form = $($(data).find('#new_user')[0].outerHTML),
$btn = $form.find('input[type="submit"]');
// Wrap the modal content in the form.
// Give the modal a unique ID.
$modal.attr('id', 'register-modal');
// Add the inputs from the form inside the body
$modal.find('.modal-body').append($form);
// Customize the title
$modal.find('.modal-title').text('Sign Up!');
// Add the submit button next to the close button
$btn.addClass('btn btn-primary');
// since the button is not actually in the form we add an event handler to submit the form.
$btn.click(function(){
$modal.find('form').submit();
});
$modal.find('.modal-footer').append($btn);
// Attach the modal to document
$('body').append($modal);
// Open the modal
$modal.modal({});
});
promise.fail(function(jqXHR, textStatus, errorThrown){
console.error('Failed to fetch user registration form', textStatus, jqXHR, errorThrown);
});
});
});
请使用您单击“提交”时生成的参数日志更新您的帖子。从表单标记中删除remote:true
-它将使用rails ujs驱动程序使用ajax发送表单。@max,删除“remote:true”与通过发送数据一样有效,但现在我收到一个错误消息:没有路由匹配[post]“/home”。你认为我需要安装“js路由”gem还是什么东西,让我在不在“/users”上时发布“页面?不,您很可能只需要添加正确的路线。请将routes.rb添加到问题中。您还需要创建表单绑定到的@user=user.new
模型实例。但是如果我是你的话,我实际上会从/users/new
加载带有ajax的表单,然后加入到模式中。它比设置ApplicationController
和layout.html.erb
来处理呈现用户注册表单要干净得多。@max,好的,我已经更新了我的原始帖子,将我的routes rile和用户模型文件包括在内。我将研究使用不同的方法。谢谢,这是我想要的更多!出于某种原因,模态体只是一个搜索框。我想知道jQuery是否只是从导航栏中的搜索框中选择了role=“form”
。是的,这很可能是case-use$form=$($(数据)。find(“#new_user”)[0]。outerHTML)
,或者无论表单的id是什么。我使用的选择器非常松散,它只是从页面中选择了第一个表单。太棒了!谢谢@max!