2010-08-04 69 views
3

假设您有一个Web应用程序,人们可以在其中提交链接,链接为他们自己的网站以及他们不拥有的网站的链接。提交表单在两种情况下都几乎相同,除非他们提交链接的域名。Rails:在提交后保留参数

如果用户从他们自己注册的网站列表中提交,他们会得到他们网站的下拉列表。

如果用户正在提交链接,用户将该域输入到我通过attr_accessor获得“链接”模型中的值的字段中。 “链接”模型然后在该域上执行find_or_create方法。

我现在的解决方案是不令人满意的: 当用户点击“提交链接”我把其他=提示到URL,然后有这样的条件:?

<% if params[:other] == "prompt" %> 
    <div class="prompt_form"> 

<h2>This link is for:</h2> 
<span class="blue_button"><%= link_to "My Website", new_link_path%></span> <span class="blue_button"><%= link_to "Another User's Site", new_link_path(:other => "yes")%></span> 
</p> 

当用户做出选择在表单中的两个选项之间呈现不同:

<% if params[:other] == "yes" || current_user == nil %> 
        <strong>Website Domain:</strong><br /> 
        <%= f.text_field :unclaimed_domain %><br /> 
      <% elsif current_user %>   
       <% if current_user.websites.size > 1 %> 
        <p> 
         <strong>Website Domain:</strong><br /> 
         <%= f.collection_select :website_id, current_user.websites.valid, :id, :domain, {:include_blank => true} %> <%= error_message_on :link, :website %><br /> 
         <%= link_to "Add a Website", new_website_path %> 
        </p> 
       <% else %> 
        <p> 
         <strong>Website Domain:</strong><br /> 
         <%= f.collection_select :website_id, current_user.websites.valid, :id, :domain %><br /> 
         <%= link_to "Add a Website", new_website_path %> 
        </p> 
       <% end %> 

这样做的问题是,如果用户进行了错误和失败一些验证,在“渲染:行动=>‘新’”的代码会被执行并且所有参数中的信息会丢失。有没有办法保持这些信息或者完全不同的方式?

回答

5

我有你只是问题的模糊认识,但似乎你想要这个:

<input name="other" value="<%= params[:other] %>" type="hidden"> 

这样,other电流值将被重新提交,并且,如果验证失败,它仍然会访问。

+0

太棒了,这完全有效。 – 2010-08-04 00:54:01

+0

有点清洁: '<%= hidden_​​field_tag:other,params [:other]%>' – 2016-04-27 21:35:47