Form doesn't work when adding :remote => true - ruby-on-rails-3

It's not the only remote form I'm using, but I can't see the problem here. It's a simple table where every row has its own form and inline form fields.
<% for temporary_address in #temporary_addresses %>
<tr id="row-<%= temporary_address.id -%>">
<%= form_for temporary_address, :remote => true do |form| %>
<td>
<%= link_to "x", temporary_address, :method => :delete, :remote => true %>
<%= form.submit "s" %>
</td>
[... form fields ...]
<% end %>
</tr>
<% end %>
However, this only works when :remote => true is not used.
resources :temporary_addresses
is in the routes file. Delete links are working and the form is also working when not using :remote => true.
pressing submit with remote => true gives
Started POST "/temporary_addresses/12" for 127.0.0.1 at 2011-07-17 12:45:26 +0200
ActionController::RoutingError (No route matches "/temporary_addresses/12")
and submitting without remote => true works with the following response
Started POST "/temporary_addresses/12" for 127.0.0.1 at 2011-07-17 12:46:15 +0200
Processing by TemporaryAddressesController#update as HTML
Parameters: {[...] "commit"=>"s", "temporary_address"=>{[...]}, "id"=>"12"}
does someone have a clue about this?
EDIT 1
Removed the link_to :remote to destroy a record to check. Same error...
A rendered form looks like this:
<tr id="row-1">
<td>
</td>
<form accept-charset="UTF-8" action="/temporary_addresses/1" class="edit_temporary_address" data-remote="true" id="edit_temporary_address_1" method="post">
<div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" />
<input name="_method" type="hidden" value="put" /><input name="authenticity_token" type="hidden" value="vpFbYO7L9fVtBsWej37FUBobraYjjdWA/F8AjWTwC7A=" />
</div>
<td>
<input id="temporary_address_firstname" name="temporary_address[firstname]" size="30" type="text" value="John" />
</td>
<td>
<input id="temporary_address_lastname" name="temporary_address[lastname]" size="30" type="text" value="Doe" />
</td>
<td>
<input id="temporary_address_email" name="temporary_address[email]" size="30" type="text" value="john.doe#example.com" />
</td>
<td>
New record
</td>
<td>
<input id="temporary_address_submit" name="commit" type="submit" value="save" />
</td>
</form>
</tr>

Solved!
Simple thing.. Firefox rearranges things when they're not valid html. The output given above is the source code. Now that I've seen the generated source code (thanks to web development toolbar) the problem is clear: The hidden form fields, generated in divs with display:none have been moved outside of the form.

Related

Added submit button calls the earlier button's function itself

I'm working on Rails 3 app. Here a view displays all the excel files uploaded by user. A button to execute all the checkbox selected files was already present with delete for each file separately. Now I'm supposed to add a 'delete' button to delete the selected files. I've added the button n modified the function called by this form jus to display "in execute" and "in delete" for now to check if the second 'delete' button is functioanal. But every time delete is clicked it prints "in execute" only in cmd. I guess the AJAX related code written in the view 'list' is the problem.
Pls help!! Tell me why is it going to execute always?
The related code is here:
PS: I hav used if params[:commit]="Delete" & if params[:delete_button] also in controller.rb to but didnt help
list.html.erb (the view that displays all files)
<% if #files.length > 0 %>
<h2 id='comments'>Uploaded Excel Files are as listed below for Edit/Delete/Execution</h2>
<div id='checkone' class='hide'>Please check atleast one excel file to execute</div>
<% ajax_str = "new Ajax.Request('/account/execute_testcases', {asynchronous:true, evalScripts:true, onComplete:function(request){adjust_sidebar();Element.show('msg');Element.hide('waitid');Element.hide('disableexecuteid');Element.show('executeid');}, onLoading:function(request){Element.show('waitid');Element.hide('msg');Element.hide('executeid');Element.show('disableexecuteid');}, parameters:Form.serialize(this)}); return false;".html_safe %>
<%= form_for 'file_names', :url => {:controller => 'account', :action => 'execute_testcases'}, :remote => true, :html => {:name => 'frmExecute', :onsubmit => ajax_str }, :id =>'execute_tc' do |f| %>
<table>
<% if #file_count > 1 && #error_in_all_files == false %>
<tr>
<td>
<input type='checkbox' name='chkAll' onclick='checkAll();'>
<span class='text'>Check All/Decheck All</span>
</td>
</tr>
<% end %>
</table>
<table class='upload'>
<% for a in #files %>
<tr>
<td>
<% file_id = a.id.to_i %>
<% if(#excel_errors[file_id].nil? || #excel_errors[file_id].empty?) && a.file_type.to_i != 1 %>
<input type='checkbox' name = "excelfile[]" value="<%= a.excel_filename %>,<%= a.excel_filename_with_timestamp %>">
<% else %>
<input type='checkbox' name = "excelfile[]" value="<%= a.excel_filename %>,<%= a.excel_filename_with_timestamp %>" disabled=true>
<% end %>
<a href="open_excel_file/<%= a.id %>" title='Click to open' class='nodecoration'><%= a.excel_filename %></a>
</td>
<td>
<%= link_to(image_tag("/images/b_edit.png", :border => 0, :title => 'Edit'), :action => 'upload_file', :file_id => a.id) %>
</td>
<td>
<img src='/images/b_drop.png' border=0 title='Delete' onclick="return confirm('This will delete the related reports too. Are you sure to delete?');">
</td>
<td>
<%
if !#excel_errors[file_id].nil? && !#excel_errors[file_id].empty?
#joined_excel_errors = #excel_errors[file_id].join(', ')
%>
Error
<% end %>
</td>
</tr>
<tr id="excel_error_<%=file_id %>" style='display:none;'>
<td colspan=4>
<% if !#excel_errors[file_id].nil? && !#excel_errors[file_id].empty? %>
<div class="padder">
<% for error_value in #excel_errors[file_id] %>
<font color='maroon'><%= error_value %></font><br>
<% end %>
</div>
<% end %>
</td>
</tr>
<% end %>
<tr><td> </td></tr>
<tr>
<td>
<% if #error_in_all_files == false %>
<span class='executebutton' id='executeid'>
<%= f.submit "Execute", name: 'execute_button', :onclick =>"return checkSelected();" %>
</span>
<span class='deletebutton' id='deleteid'>
<%= f.submit "Delete", name: 'delete_button', :onclick =>"return checkSelected();" %>
</span>
<% end %>
<span id='disableexecuteid' class='executebutton' style='display:none;'>
<input type='submit' value="Execute" disabled="disabled">
</span>
<span id='waitid' style="display:none;" class='text'>
<br>Executing Test Cases...Please wait...<%= image_tag("/images/wait26trans.gif", :border => 0) %>
</span>
<span id='msg' style="display:none;" class='text'>
<br><br> Click here to <%= link_to 'View Test Results', {:controller => 'account', :action => 'recent_test_results'}, :class => 'brownlink' %>
</span>
</td>
</tr>
</table>
<span id='subject_list'>
</span>
<% end %>
<% else %>
No test case sheets found!
<br><br>
<%= link_to '>> Upload File', {:controller => 'account', :action => 'upload_file'}, :class => 'brownlink' %>
<% end %>
<% for i in 1..10 %>
<div> </div>
<% end %>
controller.rb
def execute_testcases
if !params[:execute_button].nil?
puts "in execute"
# file_names = []
# originalfile_filewithtime = []
# original_file_map = {}
# originalfile_filewithtime = params[:excelfile]
......
# SOME CODE HERE
......
# render :update do |page|
# page.replace_html :subject_list, :partial => 'show_output', :locals => {:new_file_map => #new_file_map}
# page.visual_effect :highlight, 'subject_list', :duration => 2
# flash[:display]=#execmsg
#end
# puts #execmsg
elsif !params[:delete_button].nil?
puts "in delete"
end
end
I realised it had to do something with the Form.serialize(this) of AJAX which serialises everything. ie It calls the function of first button in the view irrespective of no of submit buttons present

Rails 3 Partial Will Not Render Via js.erb

I'm having a problem where I try to render a partial through a js.erb after I obtain some data from my controller. I've tried a number of different things, I just can't get the partial to render. The log file shows the partial rendering with a 200 OK message, but nothing happens on the page. This post is similar to the problem I am having:
Rails 3 - render partial js.erb
I have tried to follow the guidance this post, but I'm still having trouble.
Here is my partial with the form __left_date_filter.html.erb =>
<%= form_tag({:controller => 'events', :action => 'dateFilter'}, :class => 'date_form', :remote => true) do %>
<%= datepicker_input "event", :start_date, :class => 'dateFilter', :dateFormat => 'mm/dd/y' %>
<%= datepicker_input "event", :end_date, :class => 'dateFilter', :dateFormat => 'mm/dd/y' %>
<%= submit_tag "Submit" %>
<% end %>
Here is the generated HTML =>
<form accept-charset="UTF-8" action="/events/dateFilter" class="date_form" data-remote="true" method="post">
<div style="margin:0;padding:0;display:inline">
<input name="utf8" type="hidden" value="✓" />
<input name="authenticity_token" type="hidden" value="x4cbSoYnUu2+W6qvtPnKXvXR8Tp3Yh7BP9W0RMyR02g=" /></div>
<input class="dateFilter" id="event_start_date" name="event[start_date]" size="30" type="text" /><script type="text/javascript">
//<![CDATA[
jQuery(document).ready(function(){jQuery('#event_start_date').datepicker({"dateFormat":"mm/dd/y"})});
//]]>
</script>
<input class="dateFilter" id="event_end_date" name="event[end_date]" size="30" type="text" /><script type="text/javascript">
//<![CDATA[
jQuery(document).ready(function(){jQuery('#event_end_date').datepicker({"dateFormat":"mm/dd/y"})});
//]]>
</script>
<input name="commit" type="submit" value="Submit" />
Here is the dateFilter.js.erb =>
$('#content').html("<%= escape_javascript(render(:partial => 'dateFilter')) %>");
Here is the events_controller =>
def dateFilter
eventIn = params[:event]
start_date = Date.parse(eventIn[:start_date])
end_date = Date.parse(eventIn[:end_date])
sql = *redacted*
#events = Event.find_by_sql(sql)
respond_to do |format|
format.html
format.json
format.js
end
end
Here is the application.js =>
$(document).ready(function() {
$('#date_form').submit(function (){
$.ajax({
type: 'POST',
url: "/events/dateFilter",
beforeSend: function (xhr) {xhr.setRequestHeader("Accept", "text/javascript");},
data: { 'start_date' : $("input[name='event[start_date]']").datepicker(), 'end_date' : $("input[name='event[end_date]']").datepicker()}
success: function(data) { $('#content').html(response); }
});
});
This is log data from the server =>
Started POST "/events/dateFilter" for 127.0.0.1 at 2012-12-20 12:18:57 -0500
Processing by EventsController#dateFilter as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"x4cbSoYnUu2+W6qvtPnKXvXR8Tp3Yh7BP9W0RMyR02g=", "event"=>{"start_date"=>"07/01/12", "end_date"=>"07/02/12"}, "commit"=>"Submit"}
**shows SQL Statement getting all records**
Rendered events/_dateFilter.html.erb (89.1ms)
Rendered events/dateFilter.js.erb (90.7ms)
Completed 200 OK in 212ms (Views: 80.5ms | ActiveRecord: 128.2ms)
Then finally, the page I wish to render _dateFilter.html.erb =>
<div class="content">
<table class="table table-striped table-hover">
<thead>
<tr>
<th><%= sortable "event_id" %></th>
<th><%= link_to "Time Created", :sort => "event_date_time_local" %></th>
<th><%= link_to model_class.human_attribute_name(:event_type_id), :sort => "event_type" %></th>
<th><%= link_to model_class.human_attribute_name(:severity_id), :sort => "severity_name" %></th>
<th><%= link_to "Examined", :sort => "event_examined" %></th>
<th><%= link_to model_class.human_attribute_name(:action_required), :sort => "action_required" %></th>
<%#<th><%= model_class.human_attribute_name(:comments) </th>%>
<th><%= link_to model_class.human_attribute_name(:initials), :sort => "initials" %></th>
<th><%= link_to "Ticket ID", :sort => "taskid" %></th>
</tr>
</thead>
</div>
I'm just not sure why it is telling me that it rendered the partial properly, but then nothing happens on my page. I'm not very familiar with JQuery, so there is probably something wrong in my application.js or my datefilter.js.erb files.
A few things:
The ajax call is not necessary if you are using :remote => true in your form_tag. JQuery will handle the call to Rails automatically. You should be able to comment out the code in application.js.
Make sure you have a div that has id="content" in your HTML already.
It's not clear where you are getting a lot of the ruby variables in your _dateFilter.html.erb. Could you start with a simple partial to see if it works, and then you can start adding in details from the #events variable passed from the controller:
.
<div class="content">
<table>
<thead>
<tr>
<th>Test</th>
</tr>
</thead>
</table>
</div>

Pass Contest Id into URL for search in Index

I have two models, contest and submission. submission belongs_to contest and contest has_many submissions.
In the index action for submissions I have a search:
def index
contest_id = params[:contest_id]
#contest = Contest.find(contest_id)
if params[:search].blank?
#submissions = Submission.paginate(:per_page => 10, :page => params[:page])
else
#submissions = Submission.search(params[:search]).paginate(:per_page => 10, :page => params[:page])
end
#search = params[:search]
end
I think the right way to pass it in is through the search form in the submissions>index view:
<div class ="span12 row">
<%= form_tag submissions_path, :method => 'get', :class => "form-search pull-right" do %>
<%= text_field_tag :search, params[:search], :class => 'input-xlarge', :placeholder => 'Search by member, title or description' %>
<%= submit_tag "Search", :title => nil, :class => 'btn btn-primary' %>
<% end %>
</div>
And I have been able to come close using this:
<%= hidden_field :contest_id, #contest.id %>
In the form, but it's returning this in the url:
http://localhost:3000/submissions?utf8=%E2%9C%93&search=test&contest_id%5B%5D=&commit=Search
And an error:
Couldn't find Contest with id=
I've also tried this:
<%= hidden_field(:contest_id, :value => #contest.id ) %>
But it's returning similar url and error.
Right now, I'm stuck. If you have any idea, please let me know.
[edit - added html]
Before search:
<div class ="span12 row">
<form accept-charset="UTF-8" action="/submissions" class="form-search pull-right" method="get"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /></div>
<input class="input-xlarge" id="search" name="search" placeholder="Search by member, title or description" type="text" />
<input id="contest_id_5" name="contest_id[5]" type="hidden" />
<input class="btn btn-primary" name="commit" type="submit" value="Search" />
</form>
</div>
Here's what works from other links going to submissions:
From the submission show page:
<%= link_to 'Browse All Submissions', submissions_path(:contest_id => #contest.id), :class => 'btn btn-mini pull-right' %>`
and from the contest show page:
<%= link_to 'Browse All Submissions', submissions_path(:contest_id => #contest.id), :class => 'btn btn-mini pull-right' %>
Both of these pass the url "contest_id=5" which is what the controller needs to find a contest. The issue I'm having with search is finding the right syntax to get contest_id=5 to appear without the mumbo jumbo mucking it up.
This turned out to be an easy solution. Insert a hidden_field_tag in the search form:
<%= hidden_field_tag 'contest_id', #contest.id %>
This will pass the correct value into params:
http://localhost:3000/submissions?utf8=%E2%9C%93&search=new&contest_id=5&commit=Search

Rails nested_form adding items to table rows

My goal is to use the nested_form gem: https://github.com/ryanb/nested_form
but instead of creating just a new set of labels and fields every time you add an object, I wanted to insert a row into an existing table.
= nested_form_for #transaction do |f|
%h3 Line Items
%table
%tr
%th Branch
%th Department
%th Invoice #
%th Amount
%th Transaction Type
%th Deposit (y/n)
%th
= f.fields_for :line_items do |line_item|
%tr
%td
= line_item.text_field :location_id
%td
= line_item.text_field :department_id
%td
= line_item.text_field :invoice_num
%td
= line_item.text_field :amount
%td
= line_item.text_field :transaction_type
%td
= line_item.text_field :deposit
%td= line_item.link_to_remove "Remove"
%p= f.link_to_add "Add", :line_items
The .link_to_add button just creates a bunch of fields in the first row, first td.
<h3>Line Items</h3>
<table>
<tr>
<th>Branch</th>
<th>Department</th>
<th>Invoice #</th>
<th>Amount</th>
<th>Transaction Type</th>
<th>Deposit (y/n)</th>
<th></th>
</tr>
<div class="fields"><tr>
<td>
<input id="transaction_line_items_attributes_0_location_id" name="transaction[line_items_attributes][0][location_id]" size="30" type="text" />
</td>
<td>
<input id="transaction_line_items_attributes_0_department_id" name="transaction[line_items_attributes][0][department_id]" size="30" type="text" />
</td>
<td>
<input id="transaction_line_items_attributes_0_invoice_num" name="transaction[line_items_attributes][0][invoice_num]" size="30" type="text" />
</td>
<td>
<input id="transaction_line_items_attributes_0_amount" name="transaction[line_items_attributes][0][amount]" size="30" type="text" />
</td>
<td>
<input id="transaction_line_items_attributes_0_transaction_type" name="transaction[line_items_attributes][0][transaction_type]" size="30" type="text" />
</td>
<td>
<input id="transaction_line_items_attributes_0_deposit" name="transaction[line_items_attributes][0][deposit]" size="30" type="text" />
</td>
<td><input id="transaction_line_items_attributes_0__destroy" name="transaction[line_items_attributes][0][_destroy]" type="hidden" value="false" />Remove</td>
</tr>
<td>Add</td>
</div>
</table>
I've tried placing the .link_to_add in a few places, but it doesn't put them in their own row.
Is there an easy way to go about adding a row of input boxes each time?
This helped me a lot: https://github.com/ryanb/nested_form/wiki/How-To:-Render-nested-fields-inside-a-table
By default fields_for inside nested_form_for adds <div class="fields"> wrapper around every nested object. But when you need to render nested fields inside a table you can disable default wrapper using :wrapper => false option and use the custom one:
<table>
<%= f.fields_for :tasks, :wrapper => false do |task_form| %>
<tr class="fields">
<td>
<%= task_form.hidden_field :id %>
<%= task_form.text_field :name %>
</td>
<td><%= task_form.link_to_remove 'Remove' %></td>
</tr>
<% end %>
<tr>
<td><%= f.link_to_add 'Add', :tasks %></td>
</tr>
</table>
Note: You need to specify id field. Otherwise fields_for will insert it after </tr>.
Also you need to override default behavior of inserting new subforms into your form using javascript:
window.NestedFormEvents.prototype.insertFields = function(content, assoc, link) {
var $tr = $(link).closest('tr');
return $(content).insertBefore($tr);
}
A similar technique can be used for lists, for compatibility with a jQuery UI sortable list.
If you are using simple_form then add the :wrapper => false option to the surrounding simple_nested_form_for call, otherwise it gets overwritten by the :wrapper => nil default.
I ended up putting my link_to_add as the last line of the table, added this to my application.js (mostly from the example on the wiki)
jQuery(function ($) {
window.NestedFormEvents.prototype.insertFields = function(content, assoc, link) {
if($(link).hasClass('insert_in_table')){
return $(content).insertBefore($(link).parent().parent());
}
else{
return $(content).insertBefore(link);
}
};
});
My form looks like this:
<table class="tab">
<tr>
<th>My Headers</th>
</tr>
<%= f.fields_for :line_items, :wrapper => false do |form| %>
<tr class="fields">
<td>MY FIELDS</td>
</tr>
<% end %>
<tr>
<td><%= f.link_to_add "Add more line items", :line_items, :class => 'insert_in_table' %></td>
</tr>
</table>

RoR no route matches

I have this code in my routes:
controller :active_car do
put 'switch_car' => :update
get 'switch_car' => :edit
end
This is my code in on my edit page.
<% form_tag('switch_car', :method => :put) do%>
<div class="field">
<label for="car_info_id">Car Name:</label>
<%= select("", "car_info_id", #available_cars.collect {|v| [v.name, v.id]})%>
</div>
<div>
<%= submit_tag "Switch Car" %>
</div>
<% end %>
When I click submit I get the following routing error.
No route matches "/switch_car" with the url pointing to http://localhost:3000/switch_car?method=put
The get is working just fine as I end the url with switch_car I get my page to edit. For some reason the put definition is not working.
After changing method to second argument it just doesn't work. It seems to have post as the method still instead of put. Here is generated HTML
<form accept-charset="UTF-8" action="switch_car" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="_method" type="hidden" value="put" />
:method belongs to the "options" hash, which is form_tag's second argument, not the first.
http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-form_tag
Please inspect the html generated by that tag and post it here.