0

さまざまな数のランディング ページを作成するために、 high_voltageを使用しています。

これらのページには、ユーザーモデルを作成するためのさまざまなフィールドがあります。各フォームには、電子メールとランダムなその他のフィールドがあります。

例えば:

# views/pages/home1.html.erb
<%= simple_form_for(User.new) do |f| %>
  <%= f.input :email %>
  <%= f.input :first_name %>
  <%= f.button :submit, 'Sign up' %>
<% end %>

# views/pages/home2.html.erb
<%= simple_form_for(User.new) do |f| %>
  <%= f.input :email %>
  <%= f.input :last_name %>
  <%= f.button :submit, 'Sign up' %>
<% end %>

そして、Userを作成するためのコントローラーがあります。

class UserController < ApplicationController
  def create
    @user = User.new(params[:user])

    if @user.save
      redirect_to root_path
    else
      render 'pages/home' # I don't know what should be here
    end
  end
end

問題は、誰かが間違ったメールアドレスを書いたときに正しいテンプレートをレンダリングしたいのですが、今はrender 'pages/home'.

4

3 に答える 3

1

私はここで同様の投稿に答えました: 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 %>

これがすべて理にかなっていることを願っています。ご不明な点がございましたら、お気軽にお問い合わせください。

于 2013-12-06T21:55:29.477 に答える