Ruby on Rails ActionListener? - ruby-on-rails

I come from a java programming background. Currently trying to learn RoR by building a little test app. I have a database setup with a dropdown menu populated from the database. How would I get user choice from the dropdown menu?
In java it would be something like a JButton with an actionlistenr attached to it. I have my submit button figured out, but how do I attach it to my dropdown menu such that when the button is pressed it gets the user's current choice? My action/view are listed below. The end idea here is that the user selects something from the dropdown menu, clicks the submit button, and then the submit button calls another action and passes the user's choice along to to the action.
This is my index action in my controller:
def index
#ccmh = Ccmh.all
#column_names = Ccmh.columns.map {|a| a.name}
end
The action gets the model's database. It also gets the column names of the database in an array format.
This is index.html.erb:
<h1>Make Your Selections</h1>
<p>
Y-Axis
</p>
<select name="id">
<%= #ccmh.each do |abc|%>
<option value="<% abc.id %>"><%= abc.description %></option>
<% end %>
</select>
<p>
X-Axis
</p>
<select name="id">
<% #column_names.each do |a|%>
<option value ="<%#column_names.index%>"><%= a %></option>
<% end %>
</select>
<br>
<br>
<button name ="button" type ="submit">Button</button>
This creates 2 dropdown menus. One which is populatd with the value of the description column of the databse, the other is the column names themselves. The idea is that the user selects some data from the database, and then the data will be passed to another view class and rendered as a graph. Not 100% sure how I want to handle doing that as of yet, but I figured some context may help.

It needs to be in a form element. The form will determine which action the button will issue a post or get to, along with other things like the verb (post, get etc.)
Rails has helpers for these. If you post your controller and view code we can offer advice on how to make it efficient and workable.
Also try generating a scaffold. This should give you an idea how to wire up forms, buttons and inputs.
In the command-line:
rails generate scaffold Post name:string title:string content:text
would generate a model and database migration for a posts database table. It will also generate controller methods and views to allow you to edit and create them.
rake db:migrate
will create the table in your database. you can now restart your sever and play with the new pages. Try navigating to /posts and looking at the new files in the controllers and views directories.

Related

How do I use some inputted text in a html form to query a SQLite database?

How do I use some inputted text in a html form to query a SQLite database?
Forgive me, I am very new to Ruby on Rails (couple of days).
I am getting a user to enter a number followed by enter, I then want to query my SQLite db and return results to a variable. I am working in a Ruby on Rails project. Here is the code in my home.html.erb file.
<form name="myform" action="" method="get">
<input type="text" name="CardNumber" onkeypress="if(event.keyCode==13) {javascript:form.submit();>
<input type="submit" onClick="javascript:form.submit();"/>
<br>
</form>
<br>
<br>
<script type="text/javascript" language="JavaScript">
document.forms['myform'].elements['CardNumber'].focus();
</script>
First I think you'll want to do a post instead of a get. Then you need to point action to the correct route.
Usually in rails you'll have a model object instantiated on the action that renders the view with the form. Like if it's a form for creating a new User, on the controller#new action you'll have something like:
def new
#user = User.new
end
then on the view you'll have <%= form_for(#user) ... %>
Since you instantiated #user, form_for will be able to render correctly the path and action when you give it that object as a parameter. It won't be able to figure out if it's a multipart or whatever else, but the basis of routing it will.
But you don't need it obviously. Going back to your sample.
Imagine you have a route
post "save_payment_info", to: "payments#save_cc", as: :cc_save
Then a controller:
payments_controller.rb
def save_cc
cc_number_from_form = params[:CardNumber]
end
So you'll be able to access your form fields (as long as they're named correctly) on the params hash inside the controller.
You can do the same with Ajax and return a JSON response, etc.

Getting Params from raw HTML components in Rails

I'm making an input form whose features don't fit so nicely into the general form_for template rails provides. I figured I would write my own HTML mimicking the html output of form_for, but embedded with other form_for elements.
For fields I could use the rails framework for I did. For the others I made hidden fields to store what was going to Rails, and regular input fields whose values I manipulated with JavaScript to put into the hidden fields.
This is one such field:
State:<br>
<input type="text" class = "state name_input administrative_area_level_1">
<div class="field">
<input type="hidden" name="address[state]" id="state">
</div>
When I send the value of the hidden field to the console, I get a good response:
state 37
Which means the state field holds the value 37. Perfect.
Except that when I try to make my model, the params come in empty:
"state"=>"",
I do have one field that works that isn't hidden:
Street:<br><input type="text" id="street" name="address[street]">
So I changed the state input type to number, which is what it would be if it weren't hidden, but same result. Why can't rails find my param?
You can show post more detail. I can't understand 100% things you do because you write pretty simple. But i guess that you need test params name is address[state] but it's not only state becase if only state of course it nil.
if html of you rendered same up then i suggest you should put one debug in controller to see params return controller when submit form.
For example: in controller you add line:
logger.debug params
to see right params that form send.
If your form is not tied directly to a object model, it might be difficult to use the form_for helper. In those cases you should use form_tag helper. Read more about form_tag helper here.
Refer this stackoverflow answer for the difference between form_for and form_tag helpers.
Hope this helps.

Rails 3 - Simplemodal pop up with forms

I am trying to use Simplemodal as a pop up box on an index page and put a form to add a new user inside it. It's not working, says there is an undefined method. How do I make this work? Does it have to do with :remote?
EDIT - Here's some code to hopefully explain a little better - from index.html.erb
<div id='basic-modal'>
<input type='button' name='basic' value='Demo' class='basic'/>
</div>
<!-- modal content -->
<div id="basic-modal-content">
<%= render 'form' %>
</div>
My form is the standard scaffold form, my Client model has a place to add some basic information about a client. My controller is the standard controller that is generated with scaffold, and my application.html.erb adds the required .js files. When I take the
<%= render 'form' %>
out and put in just plain text, it works just fine. Does that help?
Although I haven't found the answer to using simplemodal for a modal box, I found this tutorial at Nettus which uses modalbox and facebox:
http://net.tutsplus.com/tutorials/ruby/how-to-build-an-unobtrusive-login-system-in-rails/
With a few changes for rails 3, this helped me put a form inside a modal box with no problems.

Filtering displayed records by form input

I'm super new to programming and am stuck... again,
I'm using rails 3 and currently have a venue model where each venue belongs to an area and a type (which are each thier own models) all of the venues in the database are displayed at the index page in partitions displaying the venue name, and its area and type.
How can I go about having a form with 2 dropdowns (areas and types) on the index page which filter the venue records shown depending on what is selected in the dropdowns. e.g. select pubs as type and Manchester as area and only the pubs in Manchester are shown or select pubs as type and all as area and all the pubs from all areas are shown.
I have tried installing sphinx and thinking_sphinx but can't seem to get them working on my windows 7. I got as far as a 1067 error on service startup and a "Failed to start searchd daemon." from thinking_sphinx on rake ts:start, which im presuming is from the sevice not running, so I'm hoping the answer to this won't involve sphinx.
I've had a look at scopes and am thinking this could possibly be the way to go? Although I haven't got the first idea as to how to include a dropdown to select the scope needed or indeed how to write a scope which will satisfy the kind of filter I want.
Thanks very much for any help, its much appreciated!
In your controller you should be able to do something as simple as:
#filtered_venues = Venue.where(:area => params[:venue][:area], :type => params[:venue][:type]).all
That should give you the filtered results that you want.
And then in your view you should be able to use form helpers to create the select elements:
select("venue", "area", ['New York', 'London', 'Amsterdam'], {}, { :prompt => 'Select Area' })
select("venue", "type", ['Pub', 'Outdoor', 'Hall'], {}, { :prompt => 'Select Type' })
Should output something like:
<select name="venue[area]">
<option value="">Select Area</option>
<option value="New York">New York</option>
<option value="London">London</option>
<option value="Amsterdam">Amsterdam</option>
</select>
<select name="venue[:type]">
<option value="">Select Type</option>
<option value="Pub">Pub</option>
<option value="Outdoor">Outdoor</option>
<option value="Hall">Hall</option>
</select>
There are a lot of other ways to get the options in there dynamically if you have collections ready for area or type. Check out the following for more information: http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html
You can do this in several ways, depending on how exactly you want to filter. The best is to build the filter into a .find(:conditions => ...) call and let the database do the hard work. If you don't know beforehand on what parameters you are going to filter, it's easier but less efficient to do it in code. Assuming you have search parameters venue_area and venue_type, you could do something like this in the controller:
def index
#venues = Venue.all # Or whatever criteria you might have here
#venues = #venues.select { |v| v.area_id == params[:venue_area] } if !params[:venue_area].blank?
#venues = #venues.select { |v| v.type_id == params[:venue_type] } if !params[:venue_type].blank?
...
end
You then create dropdowns containing all type and area ID:s in your search form. There are several helpers you can use for this, such as select_tag. The #options would be better populated in the controller, of course, but this shows the relationship clearer:
<form method="get">
<% #options = Area.all.map { |a| [ a.name, a.id ] } %>
<%= select_tag("venue_area", options_for_select(#options)) %>
<input type="submit" value="Filter" />
</form>
This type of filtering could be done in either JavaScript, Ruby, or both.
If the HTML itself contains all the metadata you need to determine which items match which filters, then it could be done entirely in JavaScript by hiding and showing elements in response to a change in the form.
If the user is required to click a submit button for their chosen filters to take effect, then the form could simply submit and you could repopulate the form on the back end with Rails.
If the HTML doesn't have all the metadata and you don't want them to have to submit a form, you can use AJAX to send the chosen filters to the back end, have Rails construct the new form and send it back to the client, and then use JavaScript to update the front end.
You may get a few ideas from the Railscasts episode Search, Sort, Paginate with AJAX. It's not exactly your situation, but it might point you in the right direction for how these types of operations work in general.

Multiple submit buttons/forms in Rails

I am trying to write a rails application which lets you go to a certain page, say /person/:id. On this page it shows a set of available resources. I want each resource to have a button next to it, which reserves that resource to that person (by creating a new instance of an Allocation model.) As an extension, I'd like several buttons by each resource, that cancel reservations and do other things. I'd also like to input data alongside some of the buttons, e.g. to allocate some % of a resource.
My problem is I can't work out how to sensibly do this without repeating myself, or having a very hacky controller. How can I do this without matching on the value part of the submit buttons (the text on the buttons), or using any javascript?
Additionally, if you have two forms on a page, how do you set it up so changes on both forms are saved when any submit button is clicked?
im using jQuery, and this is what i did :
<script type="text/javascript">
$(document).ready(function() {
$('#bulk_print').click(function(){
var target = '<%= bulk_print_prepaid_vouchers_path(:format => :pdf) %>';
$('#prepaidvoucher_bulk_print').attr('action', target);
$('#prepaidvoucher_bulk_print').submit();
});
$('#bulk_destroy').click(function(){
var target = '<%= bulk_destroy_prepaid_vouchers_path %>';
$('#prepaidvoucher_bulk_print').attr('action', target);
$('#prepaidvoucher_bulk_print').submit();
});
});
</script>
<% form_tag '#', :method => :post, :id => 'prepaidvoucher_bulk_print' do %>
your form details
<button class="button" type="submit" id="bulk_print">
<%= image_tag("web-app-theme/printer.png", :alt => "Print Selected Vouchers") %> Print Selected Vouchers
</button>
<button class="button" type="submit" id="bulk_destroy">
<%= image_tag("web-app-theme/cross.png", :alt => "Delete Selected Vouchers") %> Delete Selected Vouchers
</button>
<% end %>
The idea is to change the form action on the fly, based on which button is clicked
Make each row in the list a form and put the info about the item in question there. Of course, you'll need to submit and reload the page with each action. The only way around this is to use checkboxes instead of buttons and make it one big form — or to use Javascript.
As for your second question, if you want to have a submit button affect two "forms," you should make them both part of the same form. You can have multiple submit buttons on the form if you need to. Otherwise, you could dynamically generate a third form with Javascript filled with the values from the original form — but that wouldn't work in all cases (e.g., file inputs).

Resources