2017-04-25 69 views
0

我有兩種形式:如何建立部分爲具有不同的URL路徑2點的形式

<% 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傳遞給for m幫助另一個不是。

Section 10.1.1來自Rails教程建議有一種方法可以使用provide方法(「我的建議是使用變量傳遞技術」),但我找不到它。我試過傳球<% provide(:link, signup_path),然後<%= form_for(@user, url: yield(:link)) do |f| %>,但它沒有奏效。 This answer沒有提供Hartl尋找的解決方案。

感謝

回答

1

一種方式做到這一點是使用實例變量,讓你的局部知道是否應該使用默認路徑或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 
+0

它的工作原理!謝謝! – Pere

相關問題