Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Keep params after a submit

Let's say you had a web app where people could submit links, links for their own websites and links for website's that they don't own. The submission form is pretty much the same in both cases except when they submit the domain of the link.

If the user is submitting from a list of their own registered websites, they'd get a drop-down list of their websites.

If the user is submitting a link the user types the domain into a field whose value I get in the "link" model through an attr_accessor. The "link" model then executes a find_or_create method on that domain.

Right now my solution is unsatisfactory: When the user clicks "Submit Link" I put ?other=prompt into the url and then have this kind of conditional:

<% 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>

When the user makes a choice between the two options in the form renders differently:

<% 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 %>

The problem with this is that if the user makes an error and fails some validations, the "render :action => 'new'" code gets executed and all the info in the params gets lost. Is there a way to keep that info or perhaps a different way to do this altogether?

like image 298
Kenji Crosland Avatar asked Aug 04 '10 00:08

Kenji Crosland


1 Answers

I have only vague understanding of your problem, but it seems you want this:

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

This way, current value of other will be resubmitted, and, if validation fails, it'll still be accessible.

like image 120
Nikita Rybak Avatar answered Sep 17 '22 18:09

Nikita Rybak