私はここで同様の投稿に答えました:
Render partial from static page
データを送信してエラーを表示するためのコードを含むコミットは次のとおりです
。
大まかに言えば、どのフォームが送信されたかを知る方法が必要です (エラーが発生した場合に正しいフォームをレンダリングするため)。これは、コントローラーでさまざまなアクションを作成することで実現できます。
# config/routes.rb
resources :users, only: [] do
member do
post 'short_form'
post 'long_form'
end
end
コントローラーには、次の 2 つの別個のアクションがあります。
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 %>
これがすべて理にかなっていることを願っています。ご不明な点がございましたら、お気軽にお問い合わせください。