【问题标题】:Rails: Keep params after a submitRails:提交后保留参数
【发布时间】:2010-08-04 00:07:01
【问题描述】:

假设您有一个网络应用程序,人们可以在其中提交链接、他们自己网站的链接以及他们不拥有的网站的链接。两种情况下的提交表单几乎相同,除非他们提交链接的域。

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

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

目前我的解决方案并不令人满意: 当用户单击“提交链接”时,我将 ?other=prompt 放入 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 %>

这样做的问题是,如果用户出错并且未通过某些验证,“render :action => 'new'”代码会被执行,并且参数中的所有信息都会丢失。有没有办法保留这些信息,或者可能有另一种方法来完全做到这一点?

【问题讨论】:

    标签: ruby-on-rails forms


    【解决方案1】:

    我对你的问题只有模糊的理解,但似乎你想要这个:

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

    这样,other 的当前值将被重新提交,如果验证失败,它仍然可以访问。

    【讨论】:

    • 干净一点:&lt;%= hidden_field_tag :other, params[:other] %&gt;
    猜你喜欢
    • 1970-01-01
    • 2019-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-19
    • 2015-02-25
    • 2014-12-29
    • 1970-01-01
    相关资源
    最近更新 更多