我在这里回答了一个类似的帖子:
从静态页面渲染部分
这是提交数据和显示错误代码的提交:
https ://github.com/harlow/high_voltage_demo/commit/0cdbca5b0fe898d27df22787498fc7e350e81422
在高层次上,我们需要一种方法来知道提交了哪个表单(以便在发生错误时呈现正确的表单)。这可以通过在控制器中创建不同的动作来实现。
# config/routes.rb
resources :users, only: [] do
member do
post 'short_form'
post 'long_form'
end
end
控制器将有两个单独的操作:
class UserController < ApplicationController
def short_form
@user = User.new(short_form_params)
@user.save
end
def long_form
@user = User.new(long_form_params)
@user.save
end
private
def short_form_params
params.permit(:user).require(:first_name, :last_name, :email)
end
def long_form_params
params.permit(:user).require(:field1, :field2, :field3)
end
end
如果您对每个表单都使用一个局部变量,我们可以将 注入User.new
局部变量user
中。
# views/pages/home.html.erb
<%= render 'users/short_form', user: User.new %>
# views/users/_short_form.html.erb
<div id="short_form">
<%= simple_form_for user, remote: true, url: create_user_short_form do |f| %>
<%= f.input :email %>
<%= f.input :first_name %>
<%= f.button :submit, 'Sign up' %>
<% end %>
</div>
# views/users/_long_form.html.erb
<div id="long_form">
<%= simple_form_for user, remote: true, url: create_user_long_form do |f| %>
<%= f.input :email %>
<%= f.input :last_name %>
<%= f.button :submit, 'Sign up' %>
<% end %>
</div>
来自控制器的响应将呈现.js.erb
文件并检查它是否有效并返回正确的响应:
# views/users/short_form.js.erb
<% if @user.persisted? %>
# you could redirect the user with JavaScript
window.location.href = '<%= root_url %>';
# or dynamically update the content of the page to let the User know their request was submitted
$('#short_form').html('Thank you for your submission!');
<% else %>
# this will replace the contents of the Form with the errors in it
$('#short_form').html('<%= j render 'users/short_form', user: @user %>');
<% end %>
希望这一切都有意义。如果您有任何后续问题,请告诉我。