5

コードを乾かすのに役立つ_form.html.erbフォームパーシャルがありますが、新しいユーザーを作成するか、既存のユーザーを更新するかに応じて、フォームに異なるラベルを付ける必要があります。

これが私のフォームの一部です。更新中にeulaチェックボックスを表示する必要はありません。また、更新を行うときに、[アカウントの作成]送信ボタンのテキストをより適切なものに置き換える必要があります。

<% form_for @user do |f| %>
  <%= f.error_messages %>
  <p>
    <%= f.label :name, 'Full name' %><br />
    <%= f.text_field :name %>
  </p>
  <p>
    <%= f.label :username %><br />
    <%= f.text_field :username %>
  </p>
  <p>
    <%= f.label :email, 'Email address' %><br />
    <%= f.text_field :email %>
  </p>
  <p>
    <%= f.label :password %><br />
    <%= f.password_field :password %>
  </p>
  <p>
    <%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation %>
  </p>
  <p>
    <%= f.check_box :eula %>
    <%= f.label :eula, 'I agree to the terms and conditions' %>
  </p>
  <p><%= f.submit "Create my account" %></p>
<% end %>

これを行うための最良の方法は次のうちどれですか?

  • 2つの別々のフォームパーシャルがあります。1つは作成用、もう1つは更新用です。
  • 1つのフォームが部分的ですが、アクションに基づいた条件付きラベルがあります(これは可能ですか?)
  • 共通部分を部分的に分解し、作成および更新フォームで再利用します

条件付きフォームを実行する場合、どのアクションが実行されているかをどのように確認しますか?

4

2 に答える 2

13

ActiveRecord にはnew_record?、フォームに何を表示するかを決定するために使用できるメソッドがあります。

<% form_for @user do |f| %>
  <%= f.error_messages %>
  <p>
    <%= f.label :name, 'Full name' %><br />
    <%= f.text_field :name %>
  </p>
  <p>
    <%= f.label :username %><br />
    <%= f.text_field :username %>
  </p>
  <p>
    <%= f.label :email, 'Email address' %><br />
    <%= f.text_field :email %>
  </p>
  <p>
    <%= f.label :password %><br />
    <%= f.password_field :password %>
  </p>
  <p>
    <%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation %>
  </p>
  <% if @user.new_record? %>
    <p>
      <%= f.check_box :eula %>
      <%= f.label :eula, 'I agree to the terms and conditions' %>
    </p>
  <% end %>
  <p><%= f.submit @user.new_record? ? "Create my account" : "Update my account" %></p>
<% end %>
于 2009-09-22T17:59:08.860 に答える
3

呼び出し部分タグの周りに<form>タグをラップし、それぞれのビューに送信ボタンを配置します。作成ビューにeulaチェックボックスのみを配置します。

新規ビューと更新ビューで変数を作成し、それをラベル名として使用できます。

<%= f.label email, emaillabel %>

[編集]変数を部分的に渡す必要がある場合は、次を使用します。

<%= render :partial => 'form', :locals => { :myvar => myvar } %>
于 2009-09-22T15:40:31.653 に答える