Problem passing params from view to controller in Ruby On Rails - ruby-on-rails

I am new to ROR and am trying to pass two variables from two fields in a view to a controller to generate a dataset for an excel export. The excel export works, however all I get are headers and no data. I know it's because the parameters aren't being passed to the controller.
Here's the code. The SQL has been shortened...
In View
<table border="0" cellspacing="0" cellpadding="10">
<tr>
<td style="text-align: left; width:400px;"> Enter any part of a BU Manager Name, Subcontractor name, Subcontractor ID, PO Number, CRN or SCA name:</td>
<td style="text-align: left;">
<% form_tag :controller => 'subcontracts', :action => 'show_active_subcontracts_results', :method => 'get' do %>
<p>
<%= text_field_tag :search, params[:search] , :id => 'search_field' %>
</p>
<td>
<p>
Expand Contract Period:
<%= select_tag 'c_end_date', options_for_select([["Current Subcontracts", "1"],["Past 5 Years", "2"], ["All", "3"]],{:mutiple => false}) %>
<%= submit_tag "Update", :name => nil %>
<%= link_to_function "Clear", "$('search_field').clear()" %>
<%= link_to 'Export To Excel',:action=>'active_subcontracts_to_excel', :format=> 'excel' %>
</p>
</td>
<% end %>
</td>
</tr>
</table>
What I want to do is pass the 'c_end_date' and 'search' data to the controller. Not sure if the link_to is the correct way.
Thank you for your help.

Your html is invalid: between the td above your form tag you're starting another td inside the form tag where the opening td hasn't been closed yet. This could be breaking your form. Try taking that td out entirely.

Related

Pass html table td value to rails controller

In my html I'm displaying some data from two tables. I provided an edit button for each row of the table. When I click on it, it has to check if the name is existing in table1 or table2 and take all the details of that particular name.
HTML:
<div class="col-md-12">
<h5 style="text-align: center;">List of SNMP OIDs</h5>
<table id="myPersonTable" class="table table-striped" >
<thead>
<tr>
<th>Person Name</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody id="table_body">
<% #all_persons.each do |person|%>
<tr>
<td>
<%= person['name'] %>
</td>
<td>
<%= link_to '<button type="button" class="btn btn-info">Edit</button>'.html_safe, edit_oid_path(person['id'])%>
</td>
<td>
<%= form_tag(contoller: "configuration", action: "delete_person") do%>
<%= hidden_field_tag(:person_id, person['id'])%>
<%=submit_tag "Delete", class: "btn btn-danger", data: {confirm: "Are you sure?"}%>
<% end %>
</td>
</tr>
<% end %>
</tbody>
</table>
</div>
Rails Controller:
def edit
person_f = Person.find_by(name: params[:name])
person_s= HardPerson.find_by(name: params[:name])
if person_f.present?
#person = Oid.find(params[:id])
elsif person_s.present?
#oid = HardPerson.find(params[:id])
end
end
Here is a problem: I click on edit button for a person name from person2
table having id=1. This id exists in person1 and person2 tables both. Instead of taking details from person2 it is checking that id in person1 table and it is getting values for id=1 person details from person1 table
Here in controller params[:name] is getting null value. Help me to get params[:name] in my rails controller
To get params[:name] in your controller use the :param option in your routes to override the default resource identifier :id
resources :people, param: :name
This will allow you to use:
Person.find_by(name: params[:name])
Keep in mind that you might need to to override ActiveRecord::Base#to_param of a related model to construct a URL.
See 4.10 Overriding Named Route Parameters for more information.
It's a bit hard to understand what is your issue, but I'll try. Am I right that you want to see value from <%= person['name'] %> as a params[:name] inside edit action? Just pass it as additional argument to path helper:
<%= link_to '<button type="button" class="btn btn-info">Edit</button>'.html_safe,
edit_oid_path(person['id'], name: person['name'])%>

Dynamic checkbox with Ajax in Rails

I have a Form with some checkboxes loaded from the Database, and an option to add other items manually to the items table. This is done by Ajax in the code below...
item_controller.rb
def manual_item_add
#manual_item = Item.find(params[:id_item].to_i)
respond_to do |format|
format.js
end
end
manual_item_add.js.erb
$("#items_table").append("<%= escape_javascript(render 'manual_item_add', :manual_item => #manual_item) %>")
_manual_item_add.html.erb
...
<td><%= check_box_tag("manual_items[]", item.id, true) %></td>
...
edit_items.html.erb
<%= form_tag( {controller:"item", action:"edit_items"}) do %>
<p align="center">
<%= select_date(#account.start_date, prefix: 'start_date') %>
to
<%= select_date(#account.end_date, prefix: 'end_date') %>
</p>
<%= hidden_field_tag 'id_account', #account.id %>
<table id="items_table" class="subtable" align="center" width="55%">
....
<tr>
<th colspan="6">Items added manually</th>
</tr>
<tr>
<th># ID</th>
<th>Type</th>
<th>Description</th>
<th>Ammount</th>
<th>Date</th>
<th>Include in the account</th>
</tr>
</table>
<p align="center"><%= submit_tag("Save", class: "btn") %></p>
<% end %>
<%= form_tag( {controller:"item", action:"manual_item_add"}, method:"get", remote: true) do %>
<h4 align="center">Add item manually</h4>
<p align="center">Item ID:
<%= text_field_tag "item_id", nil , size:5, maxlength:5 %>
<%= submit_tag("Add Item", class: "light_btn") %>
</p>
<% end %>
So... the problem here is that though I see the new checkboxes i am adding to the table (they are being created normally), the "manual_items[]" array is not being passed to the controller when I submit the resulting form (by the way, the "items_table" is inside the form definition).
Does anybody know what I am doing wrong? Sorry for the newbie question, I'm starting to work with Ruby + Rails.
Unfortunately, I don't have a definitive answer for this problem. The only working solution I've tried was to use JQuery to force parameters to be part of the form:
$(document).ready(function() {
$("#edit_items_form").submit(function(event) {
$(this).append($("input[name='manual_items[]']:checked"));
$(this).submit();
});
});
I am definitely not comfortable to this solution, I'd like to know why these Ajax checkboxes are not automatically recognized as being part the form.

Missing template in RoR application

In my ruby on rails application, I want to get controls value into controllers page:
below is view page:
<%= form_for :managerviewresume, :url => { :method => :post, :action => :managerviewresume }) do |f| %>
<table class="table" width="100%">
<tr>
<td><%= #selection %></td> //Here I am checking radio button value
<td>
<label style="font-size:small;">Selected?</label>
<label class="radio inline" style="font-size: small">
</br>
<%= f.radio_button :select, "Yes", :id => "rb_select1" %>
Yes
</label>
<label class="radio inline" style="font-size: small">
<%= f.radio_button :select, "No", :id => "rb_select2" %>
No
</label>
</td>
</tr>
<tr>
<td>
<%= f.submit "Save", { :class => "stylbutton" } %>
</td>
</tr>
</table>
<% end %>
below is controllers page:
class ManagersController < ApplicationController
def managerviewresume
#selection = params[:select]
render "managerviewresumes"
end
end
In the controller's page I am getting below error at this line render 'managerviewresumes' :
Missing template managers/managerviewresumes, application/managerviewresumes with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :raw, :ruby, :jbuilder, :coffee]}. Searched in: * "C:/Sites/VideoResume/app/views"
below is the route:
match '/managerviewresumes', to: 'managers#managerviewresume', via: 'get'
Kindly suggest what should I do get radio button value from view page into controller page.
waiting for reply.
Thanks.
Render
Firstly, you don't need to use render to render the same view as your action name
When using a Rails controller, you can call this without issue:
#app/controllers/your_controller.rb
Class YourController < ApplicationController
def your_action
#-> will automatically render the "your_action" view
end
end
So I would remove your reference to the render action (as it is an unnecessary step). This will not resolve the issue directly, but should ensure your application is more convention over configuration
--
Routes
Secondly, you may need to look at resourceful routing
In Rails' routing structure, you are able to call resources :controller to generate a series of RESTful routes:
I understand you likely want to keep using your action, but for the sake of correctness, can I recommend you look into your config/routes.rb file & ensure you're using as many resource-based routes as possible:
#config/routes.rb
resources :managers do
collection do
post :managerviewresume
end
end
--
Form
Finally, I think your form needs to be improved
You're using form_for, which is mainly for ActiveRecord objects (if you want to create new record etc. It seems you'll be better suited to using form_tag instead:
<%= form_tag managers_managerviewresume_path do %>
<table class="table" width="100%">
<tr>
<td><%= #selection %></td> //Here I am checking radio button value
<td>
<label style="font-size:small;">Selected?</label>
<label class="radio inline" style="font-size: small">
</br>
<%= radio_button_tag :select, "Yes", :id => "rb_select1" %>
Yes
</label>
<label class="radio inline" style="font-size: small">
<%= radio_button_tag :select, "No", :id => "rb_select2" %>
No
</label>
</td>
</tr>
<tr>
<td>
<%= submit_tag "Save", { :class => "stylbutton" } %>
</td>
</tr>
</table>
<% end %>
This syntax might need checking, but this will send the :select params as required, which is not what your current form will be doing.
This should be coupled with a views/managers/managerviewresume.html.erb file for Rails to load

Rails 3 return query results to bottom of form page

I have a simple select form. When a year is selected from the form I would like the results to be returned to the same page but below the form. Can someone explain how to do this? Here is the form page (index.html.erb)
<%= form_tag("lookup/show", :method => "get") do %>
<%= label_tag(:q, "Pub Year :") %>
<%= collection_select(:lookup, :pubyear, #pubyears, :pubyear, :pubyear) %>
<%= submit_tag("Find") %>
<% end %>
Here is the show method from the Lookup controller
def show
#lookuprows = Lookup.return_lookup_row(params[:lookup][pubyear])
respond_to do |format|
format.html
end
end
Here is the show.html.erb page that the results currently go to
<tbody class="lkuptbody">
<% #lookuprows.each do |lkup| %>
<tr class="lkuprow">
<td><input type="text" class="lkupcode" value=<%= lkup.codetype %> /></td>
<td><input type="text" class="lkupdesc" value=<%= lkup.codedesc %> /></td>
<td><input type="text" class="lkuprmks" value=<%= lkup.rermark %> /></td>
</tr>
</tbody>
I understand that I will have to make a partial _show.html.erb, but how do I reference that from the form page (index.html.erb)?
Thanks
If you want the results to appear on the same page but below the form, then the form should send the results to the index action, not to the show action:
<%= form_tag("lookup", :method => "get") do %>
<%= label_tag(:q, "Pub Year :") %>
<%= collection_select(:lookup, :pubyear, #pubyears, :pubyear, :pubyear) %>
<%= submit_tag("Find") %>
<% end %>
and in your LookupController:
def index
#lookuprows = Lookup.return_lookup_row(params[:lookup][pubyear]) unless params[:lookup].nil?
...
end
Then just append the table HTML in your show page below the form (in index.html.erb) wrapped in an if block to filter out the case where #lookuprows is nil:
<% if #lookuprows %>
<tbody class="lkuptbody">
<% #lookuprows.each do |lkup| %>
<tr class="lkuprow">
<td><input type="text" class="lkupcode" value=<%= lkup.codetype %> /></td>
<td><input type="text" class="lkupdesc" value=<%= lkup.codedesc %> /></td>
<td><input type="text" class="lkuprmks" value=<%= lkup.rermark %> /></td>
</tr>
<% end %>
</tbody>
<% end %>
This will show the results in #lookuprows as a table if there are any, if not it will not show the table.
You may want to put that table HTML in a separate partial to clean up the view, but that is not essential to the problem you asked.
Hope that helps.
You want to avoid reloading the page and put it under the form? Here's how to do it with ajax :
Index.html.erb.
<%= form_tag("lookup/show", :method => "get", :data => {:remote => true, :type => "html"}, :id => "lookup_form") do %>
<%= collection_select(:lookup, :pubyear, #pubyears, :pubyear, :pubyear, id: 'lookup_show_select') %>
<%# Add More fields here %>
<%= submit_tag "Submit" %>
<% end %>
<div id='lookup_show_result'></div>
In app/assets/lookup.js.coffee. If you don't use coffeescript, it's easy to translate to JS, just ask.
$ ->
$(document).on 'ajax:success', '#lookup_form', (evt, data) ->
$('#lookup_show_result').html(data)
Controller unchanged, just process the request according to all parameters
This is a minimal untested version, tell me if you're stuck
On a side note, I'm starting to develop a gem that will extend UJS implementation of Rails with jQuery here to make standard update/delete etc easier with ajax:
jQuery UJS extended

How to Handle 2 tables with one form_tag? Rails 3

Beneficiaries
id (PK)
name
age
income
Beneficiary_loans
id (PK)
beneficiary_id (FK)
amount
rate
period
What I'm doing is, selecting a list of beneficiary from [Beneficiaries] table and displaying as follows
<%= form_tag({:action => 'update_survey_list_status', :status=>4}) do %>
<table width="100%">
<tr>
<th>Beneficiary Details</th>
<th>Amount</th>
<th>Rate</th>
<th>Period</th><th>
<input type='checkbox' name='checkall' onclick='checkedAll();'>
</th>
</tr>
<% #publishedlist.each do |b| %>
<tr>
<td><%= b.firstname %></td>
<%= fields_for :beneficiaryloan do |bloan| %>
<td> <%= bloan.text_field :amount%></td>
<td> <%= bloan.text_field :rate%></td>
<td> <%= bloan.text_field :period%></td>
<% end %>
<td><%= check_box_tag "benificiary_ids[]",b.id, :name => "benificiary_ids[]"%> </td>
</tr>
<% end %>
</table> <%= submit_tag "Approve", :class=>'form_buttons' %>
<% end %>
In controller,
#beneficiaries=Beneficiary.find(:all, :conditions => ["id IN (?)", params[:benificiary_ids]])
#beneficiaries.each do |b|
#beneficiaryloan = Beneficiaryloan.new(params[:beneficiaryloan])
#beneficiaryloan.beneficiary_id=b.id
#beneficiaryloan.hfi_id=session[:id].to_s
#beneficiaryloan.status_id=params[:status]
#beneficiaryloan.save
end
What I'm not getting is
params[:beneficiaryloan]
Values are coming as NULL
Am I missing something here in this form?
Check the following,
With the help of any browser tool(eg:firebug), make sure that the form has been rendered properly. Sometimes due to some misplaced tags(generally happens with table structure) the form does not renders properly.
Try to remove the table structure and see if the form works.
Make sure your association is fine, i guess it should be Beneficiary has many Beneficiaryloan
If none of the above helps, please post the request parameters over here.

Resources