I have answered a similar post here:
Render partial from static page
Here is the commit with the code for submitting data and displaying errors:
https://github.com/harlow/high_voltage_demo/commit/0cdbca5b0fe898d27df22787498fc7e350e81422
At a high level we'll need a way to know which form was submitted (in order to render the correct form if errors occur). This could be accomplished by creating different actions in the controller.
# config/routes.rb
resources :users, only: [] do
member do
post 'short_form'
post 'long_form'
end
end
The controller would have two separate actions:
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
If you're using a partial for each form, we can inject the User.new
as the local variable user
in the partial.
# 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>
And the response from the controller will render the .js.erb
file and check whether it's valid or not and return the correct response:
# 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 %>
Hope this all makes sense. Let me know if you have any follow-up questions.