Repopulate Form Fields in Rails Form Validation - ruby-on-rails

I have a simple user registration page in my rails app that has two fields: name and email. I have client side validation on each text field and server side for the submit button (This is the recommended way right?)
My problem is that I don't know how to repopulate the two fields with the previous values if they submitted it with a mistake. I have tried a few days such as:
format.html { redirect_to :back, :notice => 'Uh Oh! Something went wrong!', :name => #user.name } <-- create action
and
if(params.has_key?(:name))
#user.name = params[:name]
end <-- new action
Any help appreciated!

Yes this is the recommended way to put validation on both client and server side.
Regarding retaining the fields is concerned on redirect the # variables use to be get destroyed only flash persist up to one redirect.
Either u can pass your validations message in flash which is bad way the good one is to render the form page (good to be make form as seperate partial) and the # object will be automaticaly map the relevant fields like name, email.
Hope this will help you.
thanks

Add this in your form: <%= f.error_messages %> and don't redirect because you will lose the posted data.
You could do something like this in your action:
if #posted_object.save
redirect_to ...
else
render 'your view'
end

It turns out that flash can do what I wanted, but I was using it incorrectly.
I had to use:
flash[:name] = "name"
before the redirect instead of redirect_to :back, :name => "name"
and in the html
<% if flash[:name] %> instead of <% if params[:name] %> or <% name %>

Related

Rails 4 - link back to form without reloading

Rails newbie here...please be kind...
I have an app that generates a unique paragraph of text (sampled from arrays and made unique based on criteria entered in _form.html.erb, rendered from the criteria/new page). On the criteria/show page, I have 2 links, one to generate a new unique paragraph using the same criteria, and one to return to the form and edit the criteria.
For the second link, I want to retain the criteria previously entered, as the user may want to only change one entry and not have to re-enter all of it. I've found plenty of information regarding ajax calls, respond_to, remote: true, but haven't found this exact answer or if I have, my brain is TIRED and failed to comprehend.
I've seen the suggestion in a similar question (How to come back to form without reset the values?) which talks about repopulating the data: "Just add the parameters (/myForm?param1=1&param2=2&param3=3) to the button url that leads back to the search form. Then populate the fields using the parameters. No need to use session variables." Sadly, I'm unclear about how to do implement this.
Would someone please be so kind as to walk me through either (preferably the simplest!) way of doing this?
Current links on show page (commented things are those that I tried unsuccessfully:
<%= link_to 'Generate Another!', criteria_path %> #regenerates text with current criteria
<%= link_to 'Enter New Information', new_criterium_path %> #this is the link I'm trying to change
<%#= link_to 'Enter New Information', new_criterium_path, :remote => true %>
<%#= link_to 'Enter New Information', { :controller => 'Criteria', :action => "new" } :remote => true %>
Controller new action (commented until I can make it work):
def new
#criterium = Criterium.new
#testing ajax stuff
# respond_to do |format|
# format.html
# format.json
# end
end
There's lots of talk about needing a new.js.erb file (or would that be show.js.erb?) and a div tag in my show(?) page but again, brain TIRED. I've attempted some of these things, then deleted from the code so as not to gak things up too much and be unable to remember what I did.
Please tell me what else you need from me in order to answer. Many thanks in advance!
Looks like you need to pass back params to your 'new' action, and then use them when instantiating Criterium:
<%= link_to 'Enter New Information', new_criterium_path(criteria: params[:criteria]) %>
def new
#criterium = Criterium.new(criteria: params[:criteria])
end

Holding off on create action

I want to have a form that anyone can fill out, but must be logged in to submit it - if not, put the process on hold until they do.
My thought process is if someone comes across the form, it checks if they are logged in, if not the user can still fill it out, but instead prompted to log in or sign up as opposed to "Submit". If they click on either link (log in/sign up) I want it to save the form data, most likely to the session, have them log in/sign up, and then have the computer check to see if there is a saved form, and if so display a confirmation like screen, where the newly registered user can accept it.
I've posted come code below that I thought would work, but it isn't - and I was thinking that knowing rails, theres probably some convention out the to do this much faster and easier!
And I don't believe the way that I am passing the form data around is correct, so if anyone can correct me there that would be great!
View
<%= form_for :comment, :url => {:action => 'create'} %>
form fields here
<% if current_user %>
<%= f.submit "Submit" %>
<% else %>
<%= link_to "Log In", save_to_session_and_log_in_path(:comment => :comment) %> or
<%= link_to "Sign Up", save_to_session_and_sign_up_path(:comment => :comment) %>
<% end %>
Controller
def save_to_session_and_log_in_path
session[:temp_comment] = Comment.new(params[:comment])
redirect_to log_in_path
end
def save_to_session_and_sign_up_path
session[:temp_comment] = Comment.new(params[:comment])
redirect_to sign_up_path
end
User* Controller
def create
#Normal create action, under the redirect:
if session[:temp_comment]
redirect_to confirm_comment
else
redirect_to users_home_page
end
end
The error I am receiving is:
ActiveRecord::RecordNotFound in CommentsController#show
Couldn't find Comment with id=save_to_session_and_log_in
Rails.root: scrubbed
Application Trace | Framework Trace | Full Trace
app/controllers/comments_controller.rb:87:in `show'
Request
Parameters:
{"comment"=>"comment"
"id"=>"save_to_session_and_log_in"}
I've tried tweaking it every which way but it still keeps getting me here so I am unable to test if any of my code is working
What are your CommentsController#create and #show action? About your error, could you paste the rake routes result for the save_to_session_and_log_in_path and the save_to_session_and_sign_up_path methods? Since you don't have an id at that moment, you should set them as collection routes.
--
The way I'd do it, though, is submitting the form to different controllers that will handle each scenario. That way, your CommentsController will be for logged in users and you can have a TemporaryCommentsController that will take care of comments made by guests.
--
Also, depending on the comment's field, I don't know if it's a great idea to store them in the session. You could probably store a tmp_comment_id in the session and recover that from the DB. Also, delete all records with a cron-job. (This is a problem only when "the comment is big and 'hard' to serialize" though).

"Couldn't find <object> without an ID"

I'm having problems implementing a kind of comments form, where comments (called "microposts") belong_to both users and posts, users have_many comments, and posts (called "propositions") have_many comments.
My code for the comments form is:
<%= form_for #micropost do |f| %>
<div class="field">
<%= f.text_area :content %>
</div>
<div class="actions">
<%= f.submit "Submit" %>
</div>
<% end %>
The MicropostsController has this in the create action:
def create
#proposition = Proposition.find(params[:proposition_id])
#micropost = current_user.microposts.build(params[:micropost])
#micropost.proposition = #proposition
if #micropost.save
flash[:success] = "Contribution submitted"
redirect_to root_path
else
#feed_items = []
render 'pages/home'
end
end
The form for creating a new micropost is on the same page as a proposition, yet the proposition id doesn't seem to get passed at any point.
This is the error I get on submitting the micropost form:
ActiveRecord::RecordNotFound in
MicropostsController#create
Couldn't find Proposition without an
ID
Parameters are:
{"commit"=>"Submit",
"micropost"=>{"proposition_id"=>"",
"content"=>"First comment"},
"authenticity_token"=>"TD6kZaHv3CPWM7xLzibEbaLJHI0Uw43H+pq88HLZFjc=",
"utf8"=>"✓"}
I'm completely new to rails and very new to coding anything at all, so I'd be grateful for any help you can give me!
Thanks in advance.
Your params are:
"micropost"=>{"proposition_id"=>"", "content"=>"First comment"}
So to get proposition_id, you have to do :
params[:micropost][:proposition_id]
But this is empty. And there is nowhere else to get this id, that's why this line retrieves nil:
#proposition = Proposition.find(params[:proposition_id])
Making this fail:
#micropost.proposition = #proposition
You must either:
add the proposition_id as an hidden_field
store it in session
But I don't know your context enough to give you the proper solution here.
EDIT:
In your link, replace:
<%= f.hidden_field :proposition_id %>
with:
<%= f.hidden_field :proposition_id, :value => #proposition.id %>
If it doesn't work, show your params.
Note: it's bad practice to rely on instance variables, you should send local variable to each partial
As you can see, the proposition_id parameter is empty, so your controller can't find the proposition unless you give it a valid id.
You need to make sure your new form sends the proposition_id attribute. One way to do this is:
Set the proposition in the new action in the controller: #micropost.proposition = ...
In the form, add a hidden field for the id: f.hidden_field :proposition_id
In the create action, find the appropriate Proposition with params[:micropost][:proposition_id]
(You'll also want to make sure to use attr_accessible in your Micropost model, and make sure proposition_id is NOT in that list. Otherwise, you'll be open to nasty security holes. See http://www.kalzumeus.com/2010/09/22/security-lessons-learned-from-the-diaspora-launch/ and Which fields should be protected from mass assignment?)
EDIT (due to comment):
Your new action should be like this:
def new
#micropost = Micropost.new
#micropost.proposition_id = params[:proposition_id]
This is slightly different from what is said above, and is due to the fact you're sending the proposition id in the request to new. There's no need to look up the actual proposition record, since we're only interested in the id field (which we already have).

Rails: Restoring contents of non-model form that uses form_tag

I'm making good progress with my first Rails app (using Rails 3). The MVC interaction is all going fine, but I'm having difficulty with a form that doesn't relate directly to a model.
I'm using form_tag, and in the case of success, everything behaves fine. However, the handling of errors is somewhat unfriendly. The actual error message is stored in the flash and displayed fine by layouts/application.html, but I'd really like it if the form could remember the contents that the user had just filled in. But it doesn't: all the fields reset to their default values.
I love the way that forms for RESTful actions on objects automatically remember their submitted values, and get highlighted in red if there are errors. I'm fine without the red highlight, but I'd really like it if I could make the form's fields keep the submitted values.
Can anyone advise how to do this?
Excerpts from the relevant files:
views/cardsets/import.html.erb:
<%= form_tag :action => :import_data, :id => #cardset do %>
...
<%= text_field_tag "separator", "", :maxlength => 1 %>
...
<%= text_field_tag "formatting_line" %>
...etc (more fields)
controllers/cardsets_controller.rb:
# POST /cardsets/1/import_data
def import_data
success, message = #cardset.import_data(params, current_user)
if success
redirect_to(#cardset, :notice => message)
else
flash.now[:error] = message
render :import
end
end
The second arg to text_field_tag is the value to fill in the field with. Try something like this:
<%= text_field_tag "separator", params[:separator], :maxlength => 1 %>
If your field has a default, you will want to set it from the "show" action for the form:
# GET
def show_form
params[:key] = 'default'
end
# POST
def validate_form_and_act
# Don't set it here to reuse what the user passed.
end
or directly on the template (less good because uses an || every time and adds more controller data to view):
<%= text_field_tag 'name', params[:key] || 'default' %>

collection.build of nested attribute through a remote_link does not create params when submitting form

I have the following model:
class Activity < ActiveRecord::Base
has_many :clientships, :dependent => :destroy, :after_add => :default_client_info
accepts_nested_attributes_for :clientships, :allow_destroy => true
end
In my controller, if I perform the following
def new
#activity = IndividualActivity.new(params[:activity])
#activity.clientships.build(:client => Client.first)
...
end
and then save the form, it creates the relevant params and submits successfully.
However, if I chose to call the following through a remote link
#activity.clientships.build(:client => Client.last)
the view is updated with the new clientship record but when I submit the form, the params[:activity] is not created for the second nested attribute. (Why not!?)
This is the view:
%h1 Create a new Activity
- form_for #activity do |f|
%div
= render "activities/client_selector", :f => f
%div
= f.submit "Save!"
Here is the remote_link's controller action
def add_client
#activity = IndividualActivity.new(session[:individual_activity])
# Refresh client
#activity.clientships.build(:client => Client.find(params[:client_id]))
respond_to do |format|
format.js
end
end
This is the add_client.html.js:
page.replace_html "selected_clients", :partial => 'activities/clients'
This is the activities/clients partial:
- form_for #activity do |f|
- f.fields_for :clientships do |client_f|
%tr
%td= client_f.hidden_field :client_id
%td= client_f.object.client.full_name
Does anyone know how I can troubleshoot this further? I seem to have come to a dead-end with my debugging... One thing to note, there is a double use of the following form_for used in new.html.haml and the activities/clients partial (is this problematic?)
- form_for #activity do |f|
I am on rails v2.3.5
Thanks
You ask about debugging, so the first step may be looking at the server log (log/development.log).
There you should see the "params" hash.
Maybe your params contain "activity"=>{"client_id"=>..} instead of "client_id"=>.. ?
Also look at the generated HTML page - use a Firebug or just use a "view source" method of your browser. Look, especially, for input names.
If everything looks OK, put a few debug calls in your action, and look at the development.log for some database activity - do the SQL queries look like they are doing what you want?
In your question there is no 'save' method. The 'build' method does NOT save the created record. Maybe this is your problem?
def add_client
logger.debug "Creating Activity"
#activity = IndividualActivity.new(session[:individual_activity])
logger.debug "Building clientship"
# Refresh client
#activity.clientships.build(:client => Client.find(params[:client_id]))
logger.debug "#activity = #{#activity.inspect}"
# Maybe you were missing this part of code?
logger.debug "Saving #activity"
#activity.save! # use a ! to easily see any problems with saving.
# Remove in production and add a proper if
logger.debug "Saved. #activity = #{#activity.inspect}"
respond_to do |format|
format.js
end
end
You should create a functional test (in case you haven't already) and ensure that if you send proper parameters, your action works as intended.
The test will narrow your search. If the test fails, you know you have a problem in the action. If the test is OK, you need to ensure the parameters are sent properly, and you probably have the problem in your view.
UPDATE:
You said you have TWO forms on the page. This may be the problem, since only one form may be sent at a time. Otherwise it would need to work in a way which can send two requests in one request.
First thing (useful in all similar problems): validate whether your page has correct HTML structure - for example http://validator.w3.org would be a good start. Try to make the code validate. I know that some people treat a "green" status as a unachievable mastery, but just it's really not so hard. With valid code you may be sure that the browser really understands what you mean.
Second: Place all your inputs in a single form. You have problems with nested attributes. For start, try to manually insert inputs with name like <input name="activity[clientship_attributes][0][name]" value="John"/>, and for existing clientships ensure that there is an input with name = activity[clientship_attributes][0][id].
This is the way nested attributes are handled.
Your view may create such fields automagically. This construction should be what you need: (it worked in one of my old project in rails 2.x, I have just replaced the names with ones you use)
<% form_for(#activity) do |f| %>
<p><%= f.text_field :activity_something %></p>
<% #activity.clientships.each do |clientship| %>
<% f.fields_for :clientships, clientship do |cform| %>
<p><%= cform.text_field :name %></p>
<p><%= cform.text_fiels :something %></p>
<% end %>
<% end %>
<% end %>
If you really want to use a partial there, don't create a new form in the partial. Use only the parts of above code.
To pass a variable to the partial, use :locals attribute in the place where you call render :partial:
<%= render :partial => 'clientship', :locals => {:form => f} %>
Then, in your partial, you may use a local variable form where you would use f outside of the partial. You may, of course, map the variables to the same name: :locals => {:f => f}

Resources