Creating & accessing a simple Ruby on Rails Form - ruby-on-rails

I want to create the following:
The user types a text into a TextField and clicks 'submit'.
The text is then given to my ruby application which modifies certain bits of it and then displays it on the website.
The problem I am having is that I do not know how to create this textfield and how to access the content of that textfield in my application.
(All the tutorials I have looked at that use forms use a Model. Michael Hartl in chapter 7 for example writes signup page and just uses user/new as his signup page. Do I have to create a Model for my textfield as well then? It seems a bit over the top to create a model just for a simple form?)

You can just use form_tag helper to create form not connected to any model like:
<%= form_tag '/some_action_url' do %>
<%= text_field_tag 'my_field' %>
<%= submit_tag 'Send' %>
<% end %>
You can grab value of text field from params[:my_field] in your controller.

Related

How do I add autofocus to a form field if it is the edit form?

I am new to ruby on rails and working through the Rails Tutorial book and also Rails Programming from pragmatic studio. However for my project I need to find solutions now so sad I can't spend more time on the researching.
My question is, once I am able to add, show and edit forms I am being instructed to create partials, ie _forms.html.erb and then rendering those forms on the edit, show and new pages.
On my _forms.html.erb partial, how can I implement some flow using if statements based on the page that the form is being rendered for.
For example, when _form.html.erb is being rendered for the show page I want certain form_for labels/fields to be set to readonly: true. At the bottom of the form I want submit, edit, change buttons based on the page aswell.
So far I am trying to use the parems[:action] == "new" or "edit" etc to implement the control flow as follows:
Old code under the edit.html.erb file:
<%= f.label :patform_type %>
<%= f.text_field :patform_type,autofocus: true %>
New code under the _form.html.erb file:
<%= f.label :patform_type %>
<%= f.text_field :patform_type %>
<% if params[:action] == "new" %>
<%= ,autofocus: true %>
<% end %>
My original code has been influenced by these posts:
Rails not editable text field
How to disable all form_for input fields in Ruby on Rails app?
Once I get this right then I am hoping I can use it to wrap it around other elements like the submit, edit buttons etc or other fields.
Also if someone knows a better way can you please let me know as I don't know what I don't know.
Thanks for any assistance/ideas you can provide.
You probably have to stick with a bunch of if/else statements if you need such depth of logic within the form, but I would recommend having the forms typed into their respective erb file, and not be rendered from a partial with a ton of logic.
A partial is meant for repeated code, and your code is not exactly what I would describe as repeatable. It is also not immediately understandable and will contain code that is essentially a waste of time to read:
For example, if I am reading the edit action's view and I see:
if params[:action] == "new"
It will be testing for an action that isn't even relevant to the current view, unlike logic such as:
if current_user.admin?
which will be more suitable for partial-based logic.
Hope that helps, enjoy RoR

Use rails helper methods in database text

Using Rails 3.1.1
I am creating a travel guide that typically consist of "articles". In these articles I write about each place. Each article is about 500 words long and is saved as the attribute article.content in the database.
Now, I would prefer to be able to use Rails helper methods (i.e. from application_helper) and "link_to" within these articles. I can't use <%= %> simply because Rails will just interpret this as text in the article.
The main reason for me wanting to do so is to use smart internal linking (routes) and helper methods.
To clarify further:
Article is a model which has an content attribute.
a = Article.first
z = Article.last
a.content = "This is a long article where I want to place a smart link to z by using <%= link_to 'z article', article_path(z) %> and use my helper method largify so that I can <%= largify('this text') %> but I can't. What should I do?"
a.save
Is there a smart way of solving this?
<%= render inline: a.content, type: :erb %>
But beware of filling your database from untrusted sources -- someone can use it to place malicious code between <%= %>.

Create a non-database linked form field in ruby on rails

I am attempting to do some calculations on a simple ruby screen.
Lets say for fun, i want to create a form that lets the user convert meters to feet.
Of course I don't want to store the values in a database. Nor would I want to create a table just for this.
So my question.. How do I create a single text field tied to a controller.
With a button.
Here's a really simple example of making a form adding two numbers:
rails new math_app -O
cd math_app
rails generate controller Add form result
The last line generates a controller with 2 actions -
"form"- to show the form
"result" - to show the results
In another command prompt window, open the 'math_app' directory and start the server:
rails server
You can open a browser to 'localhost:3000/add/form' and 'localhost:3000/add/result' to see the default pages Rails generated for you. As you edit things below you can revisit these pages (and don't even have to restart the server) to see what they produce.
Edit 'app\views\add\form.html.erb' to create the form we want to show.
<%= form_tag add_result_path do %>
<%= number_field_tag :first %>
+
<%= number_field_tag :second %>
<%= submit_tag "add" %>
<% end %>
Edit 'config/routes.rb' to make the 'result' action take POST requests from the form above.
Change -
get "add/result"
to-
post "add/result"
Edit 'app\controllers\add_controller.rb' result method to retrieve the two numbers from the form data and add them together.
def result
#first = params[:first].to_i
#second = params[:second].to_i
#result = #first + #second
end
Edit 'app\views\add\result.html.erb' to show the result.
<%= #first %> + <%= #second %> = <%= #result %>
<br/>
<%= link_to 'back', add_form_path %>
Done!
check out form_tag http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-form_tag
Ruby on rails uses MVC ideology a lot; however you aren't required to save everything to a database form_tag allows you to create an HTML form without tying it to a model.

How can I use radio buttons properly in Rails

I am doing my first project using Ruby on Rails and need to display a set of radio buttons. It should behave exactly like a selection list. For usability reasons, I need it in a radio buttons format.
In my project, I use the collection select which also allows me to display on the edit page as follows:
select('project','project_type_id',#project_types.collect{|project_type|[project_type.name,project_type.id]}) <br>
I need something exactly like this, (especially the ability to display the selected value in the edit page) but using radio buttons.
I did a Google search and read the entire Rails guides on radio buttons but I can't find the answer.
How can I do this?
I suppose you can do it like this in your view
<% #project_types.each do |project_type| %>
<%= radio_button("project", "project_type", project_type.name) %> #assuming you have a name attribute on project_type
<% end %>
If you want a particular radio button to be checked then you can pass the checked option like so
<%= radio_button("project", "project_type", project_type.name, {:checked => true}) %>

How to show the content of the form just entered in the ":confirm =>" option on Ruby on Rails

I am trying to have a way of confirming the information entered before actually saving it to the DB
Considered making an individual confirmation page as discussed here
Ruby on Rails: Confirmation Page for ActiveRecord Object Creation
However my form includes an attached file using paperclip which makes it more of a hassle to implement.
I thought of just having a :confirm => pop up that would show the information that the user
had just entered.
The problem is how to show the information that the user had just entered, for example
<% form_for #entry, :html => { :multipart => true } do |f| %>
<%= f.error_messages %>
<%= f.label :name %><br />
<%= f.text_field :name %>
<%= f.label :file %><br />
<%= f.file_field :file %>
<%= f.submit 'Create', :confirm => "????? " %>
<% end %>
Given that your loading attachments it may not be a bad idea to render a staging view including information derived from the attachment allowing the user to confirm. As in display the file if it's an image, or the first paragraph of text if it's a text file, etc.
It's going to take more work than the just adding a confirm pop up, but I feel the enhanced user experience is worth the extra effort.
I'm not familiar with the way that paperclip works. So you're mostly on your own for the intimate details.
You will probably have to create a record before the staging view can be rendered with the sample of the uploaded file. To accomplish that I'd set up an "active" column on the model in question, that defaults to false.
Usage would look something like this:
User complets new form.
Attachment is updated and records are saved, with the active field set to false.
Redirected to confirmation page that is essentially the show page with a confirm link/button and a cancel link/button
a. When the confirm link/button is clicked it sends a request to the controller triggering the update action on this record setting active to true.
b. When the cancel link/button is clicked it sends a request to the controller trigering the destroy action on this record.
All that's left is to set up a recurring task to remove objects that are inactive and were crated long enough ago that it's safe to assume the user has just ended the browser session.
The confirm option for the Rails submit method can only take a text value.
If you want to dynamically generate the confirm text, one way you could do it is to write your own HTML submit tag, and write custom javascript to analyse the fields you want to use in your generated text.
Or you could use the Rails submit method, but use something like JQuery to add an event handler to it.
I'd just throw my js into an onclick handler. That's all Rails does.
<%= f.submit 'Create', :onclick => "confirm('Name is ' + $F('entry_name'));" %>
(note, didn't test that, but it looks close. confirm is a core js function, not part of any lib)

Resources