Enable pagination with deferLoading - ruby-on-rails

I am working in a Rails application and using the deferLoading: true option on jQuery DataTables in order pass the loading of the first DataTables to the Rails controller.
I have the datatable loading how I want it, loading the initial table in the controller gets rid of the Ajax delay when the initial html loads, however, the Datatable info section won't display the pagination results.
Code and images are shown below.
Again everything works except the pagination at the bottom of the table, I just cant get it to apply the same details as the Ajax calls to the datatable. Any ideas or direction on this issue would be greatly appreciated!
index.html.erb:
<div class="row">
<div class="col-xs-12 table-wrapper">
<div class="inner-wrapper">
<p class="quick-app">
<a class="custom-btn accent-inverse-btn add-user" href="<%= calculator_path%>">Quick Application</a>
</p>
<table class="table table-striped table-scroll cms-table-width dataTable" id="customer_deals_datatable" data-source="<%= dealer_customer_deals_url(:include_archived => params[:include_archived].present?) %>" >
<div>
<thead>
<tr>
<th>ID/Calculator</th>
<th>Applicant/Co-Applicant</th>
<th>Year</th>
<th>Model</th>
<th>App Status</th>
<th>Tier Number</th>
<th>Docs Status</th>
<th>Submitted On</th>
<th>Days Remaining</th>
<th>Chrome Decision</th>
<th>Updated At</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<% #datatable.data.each do |datum| %>
<tr>
<% datum[0] = datum[0].join('') %>
<%= (datum.map {|content| "<td>#{content}</td>"}.join('')).html_safe %>
</tr>
<% end %>
</tbody>
</div>
</table>
</div>
</div> <!-- </div>#content -->
</div>
controller
def index
respond_to do |format|
format.html do
params.merge!({"iDisplayLength"=>"10","iSortCol_0"=>"10","sSortDir_0"=>"desc"})
#datatable = CustomerDeals::CustomerDealsDataTable.new(view_context, #dealer)
end
format.json { render json: CustomerDeals::CustomerDealsDataTable.new(view_context, #dealer) }
end
end
here is a portion of the code from the datatable class in the project:
module CustomerDeals
class CustomerDealsDataTable
def fetch_deal_searches
return #deal_searches if #deal_searches.present?
deal_searches = CustomerDeals::CustomerDealSearch.where(dealership_id: #dealer )
if is_submitted_on_sort?
deal_searches = deal_searches.where('deal_dated_calculator_value != ?', 'calculator')
end
if params[:sSearch].present?
deal_searches = deal_searches.containing(params[:sSearch])
end
deal_searches = deal_searches.order(order_query)
#deal_searches = deal_searches
end
def is_submitted_on_sort?
SORT_COLUMNS[params[:iSortCol_0].to_i] == 'deal_submitted_on'
end
def lookup_sort_column
SORT_COLUMNS[params[:iSortCol_0].to_i]
end
def order_query
"#{lookup_sort_column} #{params[:sSortDir_0]}"
end
def paged_deal_searches
fetch_deal_searches.page(current_page_number).per(params[:iDisplayLength])
end
def current_page_number
params[:iDisplayLength].to_i == 0 ? 1 : params[:iDisplayStart].to_i/params[:iDisplayLength].to_i + 1
end
end
end

You're on the right track, deferLoading also can be assigned integer or array of two integers to specify how many records there are in the table for pagination to work.
From the manual:
deferLoading is used to indicate that deferred loading is required, but it is also used to tell DataTables how many records there are in the full table (allowing the information element and pagination to be displayed correctly).
In the case where a filtering is applied to the table on initial load, this can be indicated by giving the parameter as an array, where the first element is the number of records available after filtering and the second element is the number of records without filtering (allowing the table information element to be shown correctly).
Examples:
57 records available in the table, no filtering applied:
$('#example').dataTable( {
"serverSide": true,
"ajax": "scripts/server_processing.php",
"deferLoading": 57
} );
57 records after filtering, 100 without filtering (an initial filter applied):
$('#example').dataTable( {
"serverSide": true,
"ajax": "scripts/server_processing.php",
"deferLoading": [ 57, 100 ],
"search": {
"search": "my_filter"
}
} );

Related

Rails 7 paginate without sending API request

In my Rails 7 app I want to display transactions inside data table. because I expect there will be hundreds of them, I'm using pagy gem to paginate the result. Table data comes from client API request. As a response I get an array of hashes from which I extract data.
Here is my code:
Controller where I've made a request:
# transactions_controller.rb
class TransactionsController < ApplicationController
def index
response = client.transactions.list(platform_id: current_user.platform_id, page: 1, per_page: 100)
#transactions = response.body['data']
end
private
def client
#client ||= TestAPI::Client.new
end
end
Corresponding view:
#views/transactions/index.html.erb
<table class="table table-striped">
<thead>
<tr>
<b>
<tr>
<th>Date</th>
<th>Amount</th>
</tr>
</b>
</tr>
</thead>
<tbody>
<% #transactions.map do |transaction| %>
<tr>
<td>
<%= transaction['created_at'] %>
</td>
<td>
<%= transaction['amount_cents'] %>
</td>
</tr>
<% end %>
</tbody>
</table>
<%== pagy_bootstrap_nav(#pagy) %>
The pagination works well how to set it up without reloading the page? now when I use binding.pry in the controller to check if the request to the API was made, like below:
def index
response = client.transactions.list(platform_id: current_user.platform_id, page: 1, per_page: 100)
binding.pry
(...)
With each transition between pagination pages, a request is sent to the external API. How to send a request just once and operate on a single response?
[EDIT]
Controller with Low-Level Caching:
class TransactionsController < ApplicationController
def index
#pagy, #transactions = pagy_array(cashed_transactions.body['data'], items: 8)
end
private
def cashed_transactions
Rails.cache.fetch("merchants/#{current_user.platform_merchant_id}/transactions", expires_in: 12.hours) do
client.transactions.list(platform_merchant_id: current_user.platform_merchant_id, page: 1, per_page: 100)
end
end
end
Client API to get list of transactions:
def list(platform_merchant_id:, page: nil, per_page: nil, status: nil, platform_payment_id: nil)
filters = { 'filters[status]': status, 'filters[platform_payment_id]': platform_payment_id }.compact
params = { filters:, page:, per_page: }.compact
get("merchants/#{platform_merchant_id}/transactions", params:)
end

Suggestions required to improve my first use of Rails Action Cable

I have a task in my Rails app that can update a gallery album. This is passed an id that corresponds with an album on my Flickr account, it deletes all the photos attached to the album locally in the app and pulls them afresh from Flickr and updates the album name and title if required. This is required because I am currently working my way through all my photos re-tagging them all and this task will help pull those tags from Flickr to my site for searching and linking purposes.
I built an admin page that lists all my albums and each has an "Update Album" button. That looks like:
gallery.html.erb
<table class="striped">
<tr>
<th>Collections</th>
<th>Albums</th>
<th>Photo count</th>
<th>Flickr ID</th>
<th>Options</th>
</tr>
<% #collections.each do |c| %>
<tr>
<td><%= c.title %></td>
<td></td>
<td></td>
<td><%= c.flickr_id %></td>
<td></td>
</tr>
<% if c.has_albums? %>
<% c.albums.each do |a| %>
<tr class="<%= a.title.parameterize %>">
<td>↳</td>
<td>
<%= a.title %>
</td>
<td>
<%= a.photos.count %>
</td>
<td>
<%= a.flickr_id %>
</td>
<td class="this-one">
<%= link_to "Update",
admin_update_album_path(
album_flickr_id:a.flickr_id,
row: a.title.parameterize
),
"am-button": '',
method: :post,
remote: true
%>
</td>
</tr>
<% end %>
<% end %>
<% end %>
</table>
Because the task of updating took a while I thought putting it as a background job would be a good idea. Here's my controller and job:
gallery_controller.rb
class Admin::GalleryController < AdminController
def update_album
UpdateAlbumJob.perform_later(params[:album_flickr_id], params[:row])
end
end
update_album_job.rb
class UpdateAlbumJob < ApplicationJob
queue_as :default
after_perform do |job|
album = Album.find_by(flickr_id: job.arguments.first)
album.update_attribute(:updating, false)
puts job.arguments
ActionCable.server.broadcast 'album_updates_channel', content: 'Update complete', row: job.arguments[1], status: 'complete'
end
def perform(album_flickr_id, row)
require 'flickraw'
FlickRaw.api_key=ENV["FLICKR_API_KEY"]
FlickRaw.shared_secret=ENV["FLICKR_API_SECRET"]
flickr.access_token=ENV["FLICKR_OAUTH_TOKEN"]
flickr.access_secret=ENV["FLICKR_OAUTH_SECRET"]
# album_flickr_id = params[:album_flickr_id] or raise "No Album Flickr ID specified"
album = Album.find_by(flickr_id: album_flickr_id)
album.update_attribute(:updating, true)
ActionCable.server.broadcast 'album_updates_channel', content: 'Updating…', row: row, status: 'in-progress'
# Album.find_by(flickr_id: album_flickr_id).destroy if Album.find_by(flickr_id: album_flickr_id)
# Get tags
#flickr_tags_list = flickr.tags.getListUserRaw user_id: ENV["FLICKR_USER_ID"]
#tags_key = {}
#flickr_tags_list['tags'].each do |t|
#tags_key[t['clean'].to_sym] = t['raw'].first
end
# ========
# Work out parent collection
# This needs to cater for when there is NO parent collection
#collections = flickr.collections.getTree user_id: ENV["FLICKR_USER_ID"]
#parent_id = nil
def search_for_set_id_of_collection(set_id, collection, empty)
if collection["collection"]
collection.collection.each_with_index do |c|
search_for_set_id_of_collection(set_id, c, #parent_id)
end
end
if collection["set"]
collection["set"].each do |set|
if set["id"] == set_id
#parent_id = collection["id"]
end
end
end
end
#collections.each do |c|
search_for_set_id_of_collection(album_flickr_id, c, #parent_id)
end
# ========
Photo.where(album_id: album.id).destroy_all
Album.add_set_from_flickr(album_flickr_id, #parent_id, ENV["FLICKR_USER_ID"], #tags_key, true)
end
end
albumupdates.js:
const ActionCable = require('actioncable-modules');
const dotenv = require('dotenv')
dotenv.config()
const actionCable = ActionCable.createConsumer(process.env.WEBSOCKET_SERVER)
actionCable.subscriptions.create("AlbumUpdatesChannel", {
received: function(data) {
console.log('Hello from Action Cable');
if (data.status == 'in-progress') {
$('.' + data['row'] + ' td.this-one [am-Button]').hide();
$('.' + data['row'] + ' td.this-one').append(data['content']);
} else {
$('.' + data['row'] + ' td.this-one [am-Button]').show();
$('.' + data['row'] + ' td.this-one p').hide();
}
}
})
Basically, this is the first time i've just background jobs and action cable. I'm not 100% sure whether i've done this correctly but i wanted to give them a try and then ask on here for comments and suggestions. It sort of works ok but I have some questions:
Is this the best way of updating the table of albums with the status of the job? eg, "Updating..." and "Update complete!". I'd love to show an "Update Complete!" message but somehow remove that once it's been seen so just the button is showing again but unsure what path to go down to achieve that.
How would the live page updates work if i start an album updating, go away from the page and come back?
Also i'm unsure if my albumupdates.js file is set up correctly?
Just some comments and improvements to my code would be very helpful!
Thanks.

High CPU Usage when generating PDFs in Rails with Wicked_PDF gem

I'm trying to generate a PDF file with Rails, but when I do I notice my system CPU starts to max out. Initially, it will go from ~2.5% then increase to ~65%-$80% for a steady period of time and then finally max out almost prior to displaying them PDF in my iframe on my page. Here are some messages I get when monitoring the memory usage on my system:
Warning or critical alerts (lasts 9 entries)
2017-06-09 14:58:07 (0:00:04) - CRITICAL on CPU_SYSTEM (100.0)
2017-06-09 14:58:04 (0:00:13) - CRITICAL on CPU_USER (Min:72.8 Mean:83.3 Max:93.7)
2017-06-09 14:47:39 (0:00:06) - CRITICAL on CPU_USER (93.0)
2017-06-09 14:47:29 (0:00:04) - WARNING on CPU_SYSTEM (74.7)
2017-06-09 14:36:48 (0:00:04) - CRITICAL on CPU_SYSTEM (100.0)
2017-06-09 14:36:45 (0:00:10) - CRITICAL on CPU_IOWAIT (Min:78.6 Mean:85.7 Max:97.4)
2017-06-09 14:18:06 (0:00:04) - CRITICAL on CPU_SYSTEM (94.3)
2017-06-09 14:18:06 (0:00:07) - CRITICAL on CPU_USER (91.0)
2017-06-09 15:01:14 2017-06-09 14:17:44 (0:00:04) - WARNING on CPU_SYSTEM (73.8)
The gems I have installed for my PDF generation are wicked_pdf (1.0.6) and wkhtmltopdf-binary-edge (0.12.4.0). And the process with code for each are as follows:
controllers/concerns/pdf_player_reports.rb
def director_report_pdf
#players = Player.where(id: params["player_ids"]
respond_to do |format|
format.html
format.pdf do
render pdf: "#{params['pdf_title']}",
template: 'players/director_summary_report.pdf.erb',
layout: 'print',
show_as_html: params.key?('debug'),
window_status: 'Loading...',
disable_internal_links: true,
disable_external_links: true,
dpi: 75,
disable_javascript: true,
:margin => {:top => 7, :bottom => 7, :left => 6, :right => 0},
encoding: 'utf8'
end
end
players/director_summary_report.pdf.erb
<div class="document" style="margin-top: -63px;">
<% #players.each do |player| %>
<% reports = player.reports.order(created_at: :desc) %>
<% if player.is_college_player? %>
<%= render partial: 'college_director_report.html.erb', player: player %>
<% else %>
<%= render partial: 'pro_director_report.html.erb', player: player %>
<% end %>
<%= "<div class='page-break'></div>".html_safe %>
<% end %>
</div>
college_director_report.html.erb
<%= wicked_pdf_stylesheet_link_tag "application", media: "all" %>
<%= wicked_pdf_javascript_include_tag "application" %>
<% provide(:title, "#{player.football_name}") %>
<% self.formats = [:html, :pdf, :css, :coffee, :scss] %>
<style>
thead { display: table-row-group; page-break-inside: avoid }
tfoot { display: table-row-group; }
/*thead:before, thead:after { display: none; }*/
table { page-break-inside: avoid; }
tr { page-break-inside: avoid; }
.page-break {
display:block; clear:both; page-break-after:always;
}
.keep-together { page-break-before: always !important; }
.table-striped>tbody>tr:nth-child(odd)>td,
tr.found{
background-color:#e2e0e0 !important;
}
</style>
<div class="row">
<div class="col-xs-6">
<span>DIRECTOR SUMMARY</span>
</div>
<div class="col-xs-6 text-right">
<%= "#{player.full_name} / #{player.school.short_name}".upcase %>
<h1><%= "#{player.full_name(true)} (#{player.school.code})".upcase %></h1>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<%= render 'directors_report_player_header', player: player %>
<%= render 'directors_report_workouts', player: player %>
<%= render 'directors_report_grades', player: player %>
<%= render 'legacy_directors_report_contacts', player: player %>
</div>
</div>
directors_report_player_header.html.erb
<table class="table table-condensed table-bordered">
<thead>
<tr>
<th>Name</th>
<th>School</th>
<th>#</th>
<th>Position</th>
</tr>
</thead>
<tbody>
<tr>
<td><%= player.full_name(true) %></td>
<td><%= player.school.short_name %></td>
<td><%= player.jersey %></td>
<td><%= player.position.abbreviation %></td>
</tr>
</tbody>
</table>
UPDATE
I ran an example PDF generator using the following and the CPU% is what ends up maxing out as shown below...
<table class="table table-condensed">
<thead>
<th>Number</th>
</thead>
<tbody>
<% (1..60000).each do |number| %>
<tr>
<td><%= number %></td>
</tr>
<% end %>
</tbody>
</table>
Putting this in a controller seems ill-advised because the minute you deploy this the request will take a significant time to generate and block other incoming requests for other pages.
You should separate this into two concerns. One job that generates the HTML, which could be this controller, and then a background task to convert that HTML into PDF format.
In your controller, trigger a job using DelayedJob or similar and then render a page that polls for the job having completed.
Then in your background job you're dealing with just the task of rendering the HTML to PDF, rather than being within a web request. Something along these lines:
class RendersReportPdf
def self.call player_ids
html = ReportsController.render :director_report_pdf, assigns: { players: Player.where(id: player_ids }
pdf = WickedPdf.new.pdf_from_string html
temp = Tempfile.new("#{Time.now.to_i}.pdf")
temp.write(pdf)
temp.close
temp.path
# Probably upload this to S3 or similar at this point
# Notify the user that it's now available somehow
end
end
If you do this, then you can rule out that the issue is with running WickedPDF from within your controller action, but also you're making sure your site will stay up if you have long-running requests.
So I wanted to post my solution for future visitors, but it's based off of #stef's solution - so thanks stef!
controllers/concerns/players_controller.rb
def generate_report_pdf
players = print_settings(params)
pdf_title = "#{params['pdf_title']} - #{Time.now.strftime("%c")}"
GeneratePdfJob.perform_later(players.pluck(:id), pdf_title, current_user.code, params["format"])
end
app/jobs/generate_pdf_job.rb
def perform(*args)
player_ids = args[0]
pdf_title = args[1]
user_code = args[2]
report_type = args[3]
generate_pdf_document(player_ids, pdf_title, user_code, report_type)
end
def generate_pdf_document(ids, pdf_title, user_code, report_type)
# select the proper template by the report type specified
case report_type
when "Labels"
html = ApplicationController.new.render_to_string(
template: 'players/board_labels.pdf.erb',
locals: { player_ids: ids },
margin: { top: 6, bottom: 0, left: 32, right: 32 }
)
when "Reports"
# ...
end
end
def save_to_pdf(html, pdf_title, user_code)
pdf = WickedPdf.new.pdf_from_string(
html,
pdf: "#{pdf_title}",
layout: 'print',
disable_internal_links: true,
disable_external_links: true,
disable_javascript: true,
encoding: 'utf-8'
)
pdf_name = "#{pdf_title}.pdf"
pdf_dir = Rails.root.join('public','uploads','reports',"#{user_code}")
pdf_path = Rails.root.join(pdf_dir,pdf_name)
# create the folder if it doesn't exist
FileUtils.mkdir_p(pdf_dir) unless File.directory?(pdf_dir)
# create a new file
File.open(pdf_path,'wb') do |file|
file.binmode
file << pdf.force_encoding("UTF-8")
end
end
With this way I then use an ajax call to keep checking the user's specified directory for new files, and I update the partial that lists out the files in the directory. The only thing I don't like is now I have to have a table list of the user's files. I'd rather just have the file get delivered to the client's browser for download instead - but have yet figured out how to get that to work.

ROR application - pass data from view to controller

Trying to pass data from a view to controller using Javascript. How do I do this ? Specifically the information I wish to access in the controller is what option/s have been selected in a variable number (one to many) of selections on the screen.
I have a ROR application I am developing and on the "Companies - Drill Interests" screen I wish to use java/coffeescript to send data and invoke controller action. In the controller I can't get access to all the data I need to respond. That is I can' determine what "Saved Assumption" the user has selected.
From the Companies controller building array (should I be doing this or using another method) of saved assumptions.
def companies_drill_interests
# intial display use first (if present) user drill evaluations
#result_list = Array.new
#company_listings.each do |cl|
#drill_interests.each do |di|
target_share_price = 0
result = Hash.new
result["cl_display_name"] = cl.display_name
result["di"] = di.drill.name
result["target_share_price"] = 0
# if saved assumptions grab first assumption and then first target_share_price
#matched_evaluation_assumption =
EvaluationAssumption.matched_eval_assum(#current_user.id, di.drill_id)
...
# code that builds result ...
end
end
#result_list << result
end
end
end
from the screen partial views/companies/_companies_drill_interests
<%= simple_form_for #company,
html: { class: 'infogroup',
id: "x_company_drill_interests"} do |f| %>
<div class="infogroup-header">Drill Interests</div>
<div class="infogroup-body">
<table border="0" cellpadding="0" cellspacing="0" class="info">
<th class="very_large_column lalign">Drill Name</th>
...
<% if #drill_interests.present? %>
<% index = 0 %>
<% #drill_interests.each do |drill_interest| %>
<%= fields_for "drill_interest[]", drill_interest do |di| %>
<tr>
<td><%= drill_interest.drill.name %></td>
<td class="ralign"><%= drill_interest.equity_percentage %></td>
<% array_name = "evaluation_assumption" + index.to_s %>
<td id="x_user_eval_assum" class='lalign large_column' data-targets="<%= #probability_json %>">
<td> <%= select("mea_user_save_name", "id",
#assumptions[array_name].collect {|r| [ r["mea_user_save_name"], r["id"] ] },
{ :include_blank => false }) %> </td>
<% index += 1 %>
</tr>
<% end %>
...
If the user changes the "Saved Asumptions" selection this is detected in jave/coffeescript. From app/assets/javascript/companies.js.coffee
...
$('#x_company_drill_interests').change((event) ->
company_id = $('.form.companies_drill_interests').attr('data-companyid')
event.preventDefault()
calculateResult company_id
)
calculateResult = (company_id)->
data = $('#x_company_drill_interests').serialize()
$.ajax
url:"/companies/#{company_id}/projection.json",
type:"post"
...
Display statement in Companies Controller for when the action I can't get to work is performed.
class CompaniesController < ApplicationController
...
def projection
puts "================================="
puts "params = " + params.to_s
puts "================================="
...
In the logs output from this statement
params = {"utf8"=>"✓", "_method"=>"patch", "authenticity_token"=>"rFx8TBWnECUCxFiEBQ+0lTmkvhUKEJrUx/SlEQNPEP8=", "mea_user_save_name"=>{"id"=>""}, "action"=>"projection", "controller"=>"companies", "id"=>"18", "format"=>"json"}. The arrays are not present.
Overview of relationships between models.
Company has 0 to many drill_Interests. Each Drill_interest has 0 to many Evaluation_Assumptions (and using Evaluation_Assumptions I wish to display User_Evaluation_Results).
If you wish to see above you can visit the application as per instructions below.
1- go to http://quiet-fortress-3338.herokuapp.com/users/login
2- login with userid = pmlc and password = gmfive99
3- select companies from menu top RHS
4- select ADO
5- Select screen "Companies Drill Interests"
You will see ADO has an interest in both "Temp-01" and "ZZZ-Unlimited" with a number of saved assumptions for both
You are using fields_for, so change:
<td> <%= select("mea_user_save_name", "id",
#assumptions[array_name].collect {|r| [ r["mea_user_save_name"], r["id"] ] },
{ :include_blank => false }) %> </td>
to
<td> <%= di.select("mea_user_save_name", "id",
#assumptions[array_name].collect {|r| [ r["mea_user_save_name"], r["id"] ] },
{ :include_blank => false }) %> </td>
Try to use select_tag instead of select
select_tag statement
select_tag "whatever_name", options_from_collection_for_select(#assumptions[array_name].collect {|r| [ r["mea_user_save_name"], r["id"] ] }, "id", "mea_user_save_name"), include_blank: true
To send and array to backend using fields the fields must be named
<input name="myfieldarray[]">
In this way form.serialize() sends an array for myfieldarray.
check this question
How to pass an array from view to controller in Ruby on Rails
try this.
select_tag "my_array_param[]", options_from_collection_for_select(#assumptions[array_name].collect {|r| [ r["mea_user_save_name"], r["id"] ] }, "id", "mea_user_save_name"), include_blank: true

How to render the AJAX response in RAILS

Ok, pretty simple question, I have working an AJAX method, what it does is that it searches in the database for specific information with a query. I can see in the Console that the query is being made, I can even see the "Post" in the Chrome Developer Console, when I click it I can see the HTML that I want to show, but i have no effing idea on how to render ir in the page.
the :3000/ already has the html I want to show, but how do I update it??
The way I am showing it is this...
<%if not #itemsok.nil?
#itemsok.each do |searches|
%>
<table>
<tr>
<td style="width:100px;"><%= searches.first_item.description %> </td>
<td style="width:150px; font-size:30px;"><%= searches.first_item_grade %> </td>
<td style="width:150px;"><%= searches.second_item.description %> </td>
<td style="width:150px; font-size:30px;"><%= searches.second_item_grade %> </td>
<td style="width:150px; font-size:18px;">Show </td>
</tr>
</table>
#itemsok is the variable where I save the items from the query.
Thanks, I think I'm missing something very silly here.
Sorry for my terrible english.
UPDATE: The controller looks like this:
def index
size1 = params[:size1]
number1 = params[:number1]
number2 = params[:number2]
quiero = params[:quiero]
tengo = params[:tengo]
if (not number1.nil?) and (number1 != "")
item1 = Item.find(number1)
elsif not quiero.nil?
quiero.strip!
item1 = Item.find(:first, :conditions => ['lower(description) LIKE ?', "%#{quiero.downcase}%"])
end
if (not number2.nil?) and (number2 != "")
item2 = Item.find(number2)
elsif not tengo.nil?
tengo.strip!
item2 = Item.find(:first, :conditions => ['lower(description) LIKE ?', "%#{tengo.downcase}%"])
end
if (item1 and item2)
#itemsok = Contribution.where("first_item_id = ?",item1.id).where("second_item_id = ?",item2.id).where("second_item_grade = ?",size1)
respond_to do |format|
format.html
format.js
end
end
In your respond_to block put format.js above format.html.
Make sure you have index.js.erb in your view folder for the controller.
This index.js.erb(comes from the action name) should have a jQuery statement like the following if you're using rails 3.1+:
$('#DOMelementToPlaceContent').html(<%= escape_javascript(render :partial => "partial/location") %>);
This will replace the content of the DOM element with ID DOMelementToPlaceContent with the content in the specified partial.
Also, you should think about moving the logic for your search to a search action in the same controller in which case you'll need a search.js.erb file in the view folder for the controller.

Resources