如何为具有不同 url 路径的 2 个表单构建部分

How to build partial for 2 forms that have different url paths

我有两种形式:

<% provide(:title, "Edit user") %>
<h1>Update your profile</h1>

<div class="row">
  <div class="col-md-6 col-md-offset-3">
    <%= form_for(@user) do |f| %>
      <%= render 'shared/error_messages' %>

      <%= f.label :name %>
      <%= f.text_field :name, class: 'form-control' %>

      <%= f.label :email %>
      <%= f.email_field :email, class: 'form-control' %>

      <%= f.label :password %>
      <%= f.password_field :password, class: 'form-control' %>

      <%= f.label :password_confirmation, "Confirmation" %>
      <%= f.password_field :password_confirmation, class: 'form-control' %>

      <%= f.submit "Save changes", class: "btn btn-primary" %>
    <% end %>

    <div class="gravatar_edit">
      <%= gravatar_for @user %>
      <a href="http://gravatar.com/emails" target="_blank">change</a>
    </div>
  </div>
</div>

<% provide(:title, 'Sign up') %>
<h1>Sign up</h1>

<div class="row">
  <div class="col-md-6 col-md-offset-3">
    <%= form_for(@user, url: signup_path) do |f| %>
      <%= render 'shared/error_messages' %>

      <%= f.label :name %>
      <%= f.text_field :name, class: 'form-control' %>

      <%= f.label :email %>
      <%= f.email_field :email, class: 'form-control' %>

      <%= f.label :password %>
      <%= f.password_field :password, class: 'form-control' %>

      <%= f.label :password_confirmation, "Confirmation" %>
      <%= f.password_field :password_confirmation, class: 'form-control' %>

      <%= f.submit "Create my account", class: "btn btn-primary" %>
    <% end %>
  </div>
</div>

我需要创建一个部分,我已经完成了:

<%= form_for(@user) do |f| %>
  <%= render 'shared/error_messages', object: @user %>

  <%= f.label :name %>
  <%= f.text_field :name, class: 'form-control' %>

  <%= f.label :email %>
  <%= f.email_field :email, class: 'form-control' %>

  <%= f.label :password %>
  <%= f.password_field :password, class: 'form-control' %>

  <%= f.label :password_confirmation %>
  <%= f.password_field :password_confirmation, class: 'form-control' %>

  <%= f.submit yield(:button_text), class: "btn btn-primary" %>
<% end %>

但是有一个问题,即 <%= form_for(@user) do |f| %><%= form_for(@user, url: signup_path) do |f| %> 行略有不同 - 一个将 url 传递给表单助手,而另一个则没有。

Section 10.1.1 from Rails tutorial suggests there is a way to do it using the provide method ("My suggestion is to use the variable-passing technique") but I couldn't find it. I've tried passing <% provide(:link, signup_path) and then <%= form_for(@user, url: yield(:link)) do |f| %> but it didn't work. This answer 没有提供 Hartl 正在寻找的解决方案。

谢谢

一种方法是使用实​​例变量让您的部分知道它应该使用默认路径还是 signup_path。

# In your controller's action, define the following instance variable only if you want form_for's url to be signup_path
def whatever_action
  @replace_form_path = true
end

# In your view
form_for(@user, (instance_variable_defined?(:@replace_form_path) ? {url: signup_path} : {})) do
end