Advice on handling frontend User Inputs - ruby-on-rails

I've been working with Ruby & RoR for a few weeks now and must say, this is a beautiful language, it's been very enjoyable to work with.
I'm hoping someone can point me in the right direction for an article that explains collecting user inputs on the frontend, everything I've found so far has been confusing.
Basically, I want to create an input field in a front end view that passes the result to my controller so I can feed it to an API wrapper.
In irb I can do this, but I don't understand the equivalent for a view that's accessible on the front end.
customeremail = gets.chomp
ticketfind = Desk.customers(:email => customeremail)
I don't necessarily need to store the data in a database, I'd almost rather prefer not to. Basically just need the input to pass off to the API, so I can redirect to a form which I'll submit to the API. I'm certain I can figure it out with some good links, I just don't think I'm googling the right thing.
Thanks for reading!

What you want is a simple form on your view...
<%= form_tag "/my_controller/my_action" do %>
<%= text_field_tag ":customer_email" %>
<%= submit_tag "Save" %>
<% end %>
This site explains about form_tag
http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html
And in your my_controller your my_action method...
def my_action
ticketfind = Desk.customers(:email => params[:customer_email])
Unlike Josh I prefer to use form helpers, but there's always more than one way to do it.

When forms are submitted in HTML they create a POST request to the server based on the URL you pointed the form to. The server picks up the POST request and maps it to the controller via your route map.
Ex:
<!-- This will POST form data to localhost:3000/users/create -->
<form action='users/create'>
<input type='text'/>
<input type='submit'/>
</form>
This should ping your server and route to UsersController#create. Rails stashes the form data in params
http://www.w3schools.com/tags/att_form_action.asp
I would recommend that you learn to do this without ERB first. Create a form with raw HTML so you can start to learn what's going on. You can use an ERB template, but only embed the variables in Ruby (e.g. don't use form helpers). You can then refactor to that (I personally prefer raw HTML over ERB heleprs). If you use Chrome or FF, you can open up the developer console and watch how the network requests work when you submit the form (I forget if this clears with each refresh or not, so you might not actually be able to do this in this example, but it's helpful in AJAX flows)

Related

How to store html for use in rails form_for?

I've got a page with
<p class = 'new-question'> Placeholder </p>
I have a form on the same page
<%= form_for(:question, url: question_path(Question.find_by(content:))) %>
I want the value of :content to be whatever the text of the <p> class is, ie in this case it should be Placeholder, I can't just put content: "Placeholder" because the text will be changed by a js script. How should I do this?
You can't use Ruby dynamically in the web page like that. question_path(Question.find_by(content: "whatever")) only resolves once, when the page loads, and just gives you a url that plops into the form.
The right way to do this is to dynamically change the url for the form directly with JS. If you only want to figure out the url based on the content/respective content, then you have two options:
Load all the Questions at once so that they're available to your JS on page load. Once the JS has the content, it can look through those Questions to find the appropriate url (where you'll also need to figure out how the routes are arranged--it's usually something simple like /questions/1/create.
If you're willing to make additional requests, then you can more sensibly use AJAX calls to ping your DB every time the content changes and let Rails tell you (through the AJAX) exactly what url to replace with.

What are the benefits, if i use rails view form template?

Example, i made a form like this
<form name="register" method="post" enctype="multipart/form-data">
<p><h3>User check</h3></p>
<p>admin ID: <input type="text" name="userid"></p>
<p>admin Pass: <input type="password" name="password"></p>
<input type="submit" name="apply" value="Submit"></p>
<p> </p>
</form>
and my manager wants to change this form to rails form template like this,
<%= form_for(:model) do |form| %>
<p>
<%=form.label :input%>
<%=form.text_field :input, :placeholder => 'Enter text here...'%>
</p>
<%end%>
My question is, it works fine with html based front code. Why do i have to change this to rails code? I just want to keep my front-end code...I don't know why i have to change this :(. Also, I'm new on Ruby on Rails. That is the main reason. I dont' want to change the existing code, if it is working.
I really hate this job. I have to translate all the attributes to the rails code and that makes me really exhausted :(
Form builders are here to help
Form helpers are supposed to make your life simpler. They are quicker to write than their pure html alternative, provided you don't write pure html first.
They also provide a lot of easy implementations for difficult integration pieces, like :
displaying a date selection select group
mirroring the fact that a check box has been unchecked in POST params
automatically adding multipart param on form if you add a file input (not actually difficult to achieve, but easy to forget)
... and many more
Further development
All of this is about comfort, and you may think you could avoid it if you already have a perfectly working pure html implementation.
But what happen if someone later has to add a date select input in your form ? She will have to use the rails helper, since it saves a lot of time in controller part to set date in database. But she won't be able to leverage form builder, since you haven't used it.
Now, she has to choose between using a non builderdate_select tag mixed in pure html or ... to rewrite your form completely. As you may realize, mixing different styles is generally considered ugly, and we don't like ugly in ruby.
Security
Form tag helpers also provide an important security measure : CSRF protection. Every time you use a rails helper to create a <form> tag, it automatically adds an hidden input containing a secret key. That key has to be posted with form data to prove request originated from current website.
If you use plain html forms, you won't have this security. You could of course add the token manually using the correct method, but this would again be more time wasting than simply using form helpers.
Bottom line
The main problem is that you write pure html before using rails helpers - that is what is wasting time.
Some benefits of using Rails form helpers are:
Consistent naming of input elements names and ids
i18n support for labels
generated URL with form_for is less error prone
Better handling of checkboxes
Nice helpers like options_for_select
Less typing
That last ones might be my favourite: less typing.

post without changing page?

I'm thinking AJAX is probably the most logical route to my answer, but I can't find a way to use an AJAX post without making my routing convention useless. As far as I have been able to tell, using
<%= form_for(#post) do |f| %>
you can not give the form_for helper an ID- at least, not with 'do |f|' in there. If I'm understanding this line of code correctly..
$("#test").ajaxForm({url: '/posts', type: 'post'})
Then I would need to give my form tag an ID. If that is true, I could get around that by doing
<form id="test">
But then not only would I have to rename all my helpers, I would have to edit my controller to parse the data posted by the form. Given the size of my project, that could take a week... and it cuts the potential for scale to an extent.
A synopsis for why I'm doing this-
I have a form that is technically an "edit" page, but it is more of a mix of show, edit, and new. There is a mix of info from last month's work, edit boxes for last month's work, and new boxes for this month's. There are four main "blocks" to the page, and each has a separate set of information which may or may not be stored in a separate database table, which may or may not be related to any of the other tables.
It is important for employees to be able to post updates on a regular basis- every few seconds or so. However, this kills system resources as each time they post, it re-loads the entire page. I have code bashed out to use AJAX to refresh specific blocks upon button click, but it does me no good if the entire page automatically re-freshes after the post anyway. Is there a way to either disable the reload in the update action, or to post in a different manner using AJAX so that the page does not refresh/redirect?
Using rails 3.0.20
Using ruby 1.8.7 (2012-10-12 patchlevel 371)
Using Ubuntu 12.04 LTS
I would look at the form_for docs (http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_for).
The quick answer is you need to add remote: true to your form_for.

How to create one form with many possible actions in Rails?

I want to create one form with 2 buttons in rails. Both forms operate on the same data in different ways, and I would prefer to keep the associated functionality in two different methods. Previously I've redirected to the appropriate method after doing a string comparision on params[:commit], but my gut says there's a better approach. Suggestions?
Two different submit buttons that send the form to two different actions:
<%= submit_tag('Insert', :onclick=>"document.myForm.action = 'insert';") %>
<%= submit_tag('Update', :onclick=>"document.myForm.action = 'update';") %>
Instead of "myForm" you need to put whatever is in the "name" property of your tag.
You can set that property in your default form:for tag like this:
<%= form_for(#something, :html => {:name => "myForm"}) do |f| %>
Without using JavaScript, your only solution is what you mention: checking which button was clicked by looking at the POST data in the controller. This is simply due to the nature of the HTML form element. It cannot have more than one value for its action attribute.
If you're not worried about what will happen when JavaScript isn't available, then you can write some script to change the action attribute when one of the submit buttons is clicked, prior to actually submitting the form. In the case of an ajax request, it could simply submit to the correct URL directly without altering attributes on the form.
I also used the params[:commit] method on a form already. Using the I18n helpers makes this a bit less fragile as you can use the same lookup in the view and controller, so you don't encounter the problem that the string changes a bit.
Besides that I can only think of using JavaScript to handle the clicks on the buttons and then send the form data to different Rails actions (Maybe you can change the HTML action attribute of the form with JavaScript before you submit the form).
If you're using prototype.js, you can use Form.serialize() to grab your data from your form and from there use the different buttons to post to different actions.

Using HTML forms in ASP.NET MVC?

It seems like everything I look up on this subject has either changed since the release or is wildly different from eachother.
I just want to create a simple form in my view.
Should I be using the Html.BeginForm()/TextBox()/EndForm() methods or should I be using a plain-jane HTML form? Which is preferred?
This is what I have so far:
<%=Html.BeginForm("Create", "Product", FormMethod.Post); %>
<%=Html.TextBox("productTextBox", "Enter a shoe name"); %>
<input type="submit" name="createButton" value="Create Me!" />
<%=Html.EndForm(); %>
What is the "correct" way to create a simple form with a button and textbox in ASP.NET MVC and allow me to submit the data in the form to the /Product/Create action?
How do I then access the form data from within that method? Some people seem to use a "FormCollection" and others just do a Request.Form method. Which way should I use?
Can someone enlighten me?
The Form helpers are the recommended way because it allows you to provide a controller, action and other route data and the URL is auto-generated based on your routes (in Global.asax). The advantage is, if you decide to change your routes, you don't have to update every URL in your site.
The only reason I'd use an actual "<form>" tag was if I needed extra control over the markup that I couldn't get from Html.Form (I can't think of an example right now). Even if you choose to do that, you should use the "Url.Action" helper to get a URL from routing data. For example:
<form action="<%= Url.Action("Create") %>">
As for your second question, I'd suggest using the Model Binder. Check out ScottGu's Blog for some details on this.
Have a look at Link.
It's German text but the code should be understandable.
Have you looked at this:
http://weblogs.asp.net/scottgu/archive/2009/03/10/free-asp-net-mvc-ebook-tutorial.aspx
It's from the horse's mouth, and is up-to-date with the final release.

Resources