Dynamically pass Hash value to a partial - ruby-on-rails

I faced a problem to pass the hash value to partial file dynamically. I displayed the person names on my page (this is a partial). The hash value is like this:
names[1] = "James"
names[2] = "Williams"
names[3] = "Jack"
render :partial => "list", :locals => {:names => names}
I need to pass the hash value dynamically. How can I do that? In the example, the new hash is like this:
names[21] = 'Flink'
names[81] = 'Mark'
My code
class PrlcController < ApplicationController
def bar
#names = Hash.new
#names[1] = "James"
#names[2] = "Williams"
#names[3] = "Jack"
end
def foo_ajax
#names = Hash.new
#names[21] = 'Flink'
#names[81] = 'Mark'
end
end
bar.rhtml
----------
<!-- Name listing section -->
<%= render :partial => "list", :locals => "{:names => #names}" %>
<!-- AJAX calling section -->
<%= link_to_function "call testing", :onclick => "load_foo_ajax_data" %>
<!-- AJAX section -->
<div id="foo_ajax_data">
</div>
<!-- script section -->
function load_foo_ajax_data() {
new Ajax.Updater("foo_ajax_data","/Prlc/foo_ajax", {
asynchronous:true,
evalScripts:true,
onComplete:function(request){
},
onLoading:function(request){}
});
}
foo_ajax.rhtml
--------------
Some process here.
_list.rhtml
-----------
Display the names

Try following
class PrlcController < ApplicationController
def bar
#names = Hash.new
#names[1] = "James"
#names[2] = "Williams"
#names[3] = "Jack"
end
def foo_ajax
#names = Hash.new
#names[1] = 'Flink'
#names[2] = 'Mark'
render :update do |page|
page.replace_html 'foo_ajax_data', :partial => "list", :object => [#names]
end
end
end
bar.rhtml
<%= render :partial => "list", :locals => "{:names => #names}" %>
<!-- AJAX section -->
<div id="foo_ajax_data">
<!-- Name listing section -->
</div>
<!-- AJAX calling section -->
<%= link_to_remote "call testing", :url => { :action => "load_foo_ajax_data"} %>

Related

How can I display my search results in rails?

When I write city in field and click button, on page has to be that name of city and another. In my case every time name is New York. When I write for example Las Vegas my link is http://localhost:3000/?query=Las+Vegas&commit=Search, the data on the page is about New York.
class HomeController < ApplicationController
def index
require 'net/http'
require 'json'
#params = {
:access_key => "1dbc1a3aa6b2e76a0c8eda1cba0c9c8b",
:query => "New York"
}
#uri = URI("http://api.weatherstack.com/current?access_key=1dbc1a3aa6b2e76a0c8eda1cba0c9c8b&query=#{#params[:query]}")
#uri.query = URI.encode_www_form(#params)
#json = Net::HTTP.get(#uri)
#api_response = JSON.parse(#json)
if #params[:query].empty?
#city = "Enter city"
#temperature = "(in English)"
else
#city = " #{#api_response['location']['name']}"
#temperature = "#{#api_response['current']['temperature']}°"
end
end
end
routes.rb
Rails.application.routes.draw do
root 'home#index', :as => 'search'
end
index.html.erb
<div class="main">
<h1 class="weather">Weather</h1>
<%= form_with(url: search_path, method: "get", local: true) do %>
<%= text_field_tag(:query) %>
<%= submit_tag("Search",class: "btn btn-primary") %>
<% end %>
<div class="city"> <h1><%= #city %> <h5><%= #temperature %></h5></h1> </div>
</div>
It looks like you have hardcoded New York in your params.
#params = {
:access_key => "1dbc1a3aa6b2e76a0c8eda1cba0c9c8b",
:query => "New York"
}
So you need to change this to be something like:
#params = {
:access_key => "1dbc1a3aa6b2e76a0c8eda1cba0c9c8b",
:query => params[:query]
}

Submitting multiple records using AJAX

I do not have much idea on jQuery/Ajax. Could someone help me to submit the forms dynamically
here is the requirement:
- I have set of tests
- Each test has a result
- Each test result stored as separate record
I am thinking of following approach:
- display each test result as a separate form and submit each one of them using AJAX
I hope there would be a better approach, please help me
here are my code:
//results controller
class ResultsController < ApplicationController
def index
#results = Result.all
#tests = Tests.all
end
def new
#result = Result.new
end
//view
#tests.each do |test|
= form_for(#result) do |r|
= r.label :test_id, test.name
= r.hidden_field :test_id, :value => test_id
= r.select :status, options_for_select(%w[UNTESTED PASS FAIL PENDING BLOCKED INVALID])
= r.submit "Submit"
The index action from controller will call index page
In index page
= #tests.each do |test|
#test.#{test.id}= render partial: "test", :locals => {test: test}
create one _test.html page In _test page do all this,
= form_for(test) do |test|
= r.label :test_id, test.name
= r.hidden_field :test_id, :value => test_id
= r.select :status, options_for_select(%w[UNTESTED PASS FAIL PENDING BLOCKED INVALID])
= r.submit "Submit"
create one index.js.html file
:plain
$("#test_#{#test.id}").html("#{escape_javascript(render(:partial => "test", :locals => { :test => #test}))}");

Rails exporting xls using link_to format

Hello everybody who likes RAILS, i have a problem i'm trying to export by "ejecutive_id" to XLS but i'm not doing the correct code,
-I created a select box where i can select all my ejecutives.
-I created another select box where i can select by status_id.
-I selected 1 ejecutive for example "Mogan" (ejecutive_id = 1)
-I selected 1 status form example "active" (status_id = 0 )
-After selecting both select boxes i click on "SEARCH"
-After doing SEARCH i'm getting my results (#list_policies this value in my code is before respond format)
Here is my controller
****PROJECT/APP/CONTROLLER/policy_managment/policy.rb********
class PolicyManagement::PolicyController < ApplicationController
def generate_print_ejecutive_comercial
#search_ejecutive = params[:search_ejecutive]
#search_status = params[:status_id]
#list_ejecutives_comision = Ejecutive.find(:all)
#list_policies_search = Policy.deleted_is(0)
if params[:search_ejecutive].to_i!=0
#list_policies_search = #list_policies_search.ejecutive_id_is(#search_ejecutive)
end
if !params[:status_id].blank?
if params[:status_id].to_i != 3
#list_policies_search = #list_policies_search.state_is(params[:status_id])
end
else
#list_policies_search = #list_policies_search.state_is(0)
end
#status_id = params[:status_id]
if !#search_dependent_dni.blank?
if #list_dependents.blank?
#list_dependents = Dependent.id_gt(0)
end
#list_dependents = #list_dependents.num_document_is(#search_dependent_dni)
list_dependencies = []
#list_dependents.each do |dependent|
list_dependency_dependents = Dependency.find(:all, :conditions => { :dependent_id => dependent.id })
list_dependency_dependents.each do |dependency|
list_dependencies << dependency
end
end
policy_ids = []
list_dependencies.each do |dependency|
policy_ids << dependency.policy_id.to_i
end
end
#list_policies_search = #list_policies_search.deleted_is(0)
#list_policies = #list_policies_search.paginate(:page => params[:page], :per_page => 10)
#results = #list_policies_search.find(:all,:conditions=> { :ejecutive_id => #search_ejecutive })
respond_to do |format|
format.html
format.xls
format.js {
render :update do |page|
page.replace_html 'table', :partial => 'table2'
end
}
end
end
end
Here maybe could be the problem,also those are my links where i can export
*********HERE IS MY VIEW***********
<% form_remote_tag :url=>{:action=>"generate_print_ejecutive_comercial"},:before=>"load_close('loading_search')",:success=>"load_off('loading_search')" do -%>
<label>EJECUTIVES:</label>
<%= select_tag 'search_ejecutive',"<option value=\"\">Select</option>"+options_for_select(#list_ejecutives_comision.collect {|t| [t.name.to_s+" "+t.lastname1.to_s,t.id]})%>
</span>
<label>STATUS :</label>
<%= select_tag "status_id","<option value=\"3\">ALL</option>"+options_for_select([["active",0],["cancel",1],["no cancel ",2]],0) %>
</span>
<input name="Buscar" value="SEARCH" type="submit" /><span id="loading_search"></span>
<% end %>
#HERE WITH THOSE LINKS I'M EXPORTING ONLY MY FIRST 10 VALUES
<%= link_to("Export Excel","http://localhost:3000/policy_management/policy/generate_print_ejecutive/generate_print_ejecutive_comercial.xls")%>
<%= link_to "Export XLS",:controller=>"policy_management/policy",:action=>"generate_print_ejecutive_comercial",:format=>"xls" %>
<%= link_to 'PRINT PDF', :controller=>"policy_management/policy",:action=>"generate_print_ejecutive_comercial", :format=>"pdf" %>
I'm exporting my partial view and it depends of this
#list_policies = #list_policies_search.paginate(:page => params[:page], :per_page => 10)
Here is my partial view and i'm using #list_policies
********************PARTIAL VIEW THAT I WANT TO EXPORT*********
<table>
<% #list_policies.each do |policy| %>
<tr>
<td><div class="nobreak"><%= policy.num_policy%></div></td>
<td><div class="nobreak">
<% if !policy.ejecutive.blank? %>
<%= policy.ejecutive.name %><%= policy.ejecutive.lastname1 %><%= policy.ejecutive.lastname2 %>
<% end %></div>
</td>
<td><div class="nobreak"><%= policy.str_state%></div></td>
</tr>
</table>
Seems that i need to add some params to my links_to....format.... i don't know what to add
Somebody can check this code?
It seems like using an options hash to dynamically build your query might be easier / cleaner. I would do it like this:
class PolicyManagement::PolicyController < ApplicationController
def generate_print_ejecutive_comercial
#list_ejecutives_comision = Ejecutive.find(:all)
policy_options = {:deleted => false}
policy_options = policy_options.merge({:ejecutive_id => params[:search_ejecutive]}) unless params[:search_ejecutive].blank?
policy_options = policy_options.merge({:state => params[:status_id]}) unless params[:status_id].blank? and (params[:status_id] != 3)
#list_policies_search = Policy.all(policy_options)
if !#search_dependent_dni.blank?
if #list_dependents.blank?
#list_dependents = Dependent.id_gt(0)
end
#list_dependents = #list_dependents.num_document_is(#search_dependent_dni)
list_dependencies = []
#list_dependents.each do |dependent|
list_dependency_dependents = Dependency.find(:all, :conditions => { :dependent_id => dependent.id })
list_dependency_dependents.each do |dependency|
list_dependencies << dependency
end
end
policy_ids = []
list_dependencies.each do |dependency|
policy_ids << dependency.policy_id.to_i
end
end
#list_policies = #list_policies_search.paginate(:page => params[:page], :per_page => 10)
respond_to do |format|
format.html
format.xls
format.js {
render :update do |page|
page.replace_html 'table', :partial => 'table2'
end
}
end
end
end

Filtering values of index page on values defined in drop down box.rails 3

I am a newbie with rails and I am trying to fliter my index page on values selected by drop down box on index page
For Eg .In my index page I am having a drop down box showing employee names if user selects a value from drop down list the values of index page should filter with that employee name.
Note- Te Employee name is a cross reference field
My Controller Look like
def index
#complaints = Complaint.paginate(:page => params[:page], :per_page => 10)
respond_to do |format|
format.html # index.html.erb
format.json { render :json => #complaints }
end
end
My Index View Looks like
<%= select("employee", "employee_id", Employee.all.collect {|p| [ p.fullname, p.id ] }, { :include_blank => true }) %>
I have tried to answer with whatever I can understand from your question and
I am asssuming u dont want filtering through an ajax call and your complaint table consists of a column named employee_id.
In your index_view add
<%= form_tag 'controllers_index_path' , :method => "get", :id=> 'filter_employees_form' do %>
<p>
<%= select_tag 'employee_id', options_for_select(Employee.all.collect {|p| [p.fullname, p.id ] }, :selected => params[:employee_id]), :prompt => 'Select', :id => 'filter_employees' %>
</p>
<% end %>
Add the following code in the javascript file or add it at the end of your index page.
$(document).ready(function(){
$('#filter_employees').change(function(){
$('#filter_employees_form').submit();
})
})
In controller.rb
def index
#complaints = Complaint.get_complaints(params).paginate(:page => params[:page], :per_page => 10)
respond_to do |format|
format.html # index.html.erb
format.json { render :json => #complaints }
end
end
In complaint.rb(model)
def self.get_complaints(params)
conditions = ['']
conditions = ['complaints.employee_id = ?', params[:employee_id]] if params[:employee_id]
self.where(conditions)
end
Hope this is what you are looking for.

Parameter in AJAX request

I have a view which contain multiple links:
<% a.each do |q| %>
<%= link_to "stock it",
{ :action => "stock",
:qid => q.question_id,
:qur => q.question_answers_url,
:qti => q.title } ,
:remote => true %>
<div id="<%= "stock" + q.question_id.to_s %>"></div>
<% end %>
Each link generate AJAX-request. Here is a controller:
def stock
if(!Later.where(:question_id => params[:qid]).exists?)
later = Later.new(:question_id => params[:qid], :name => params[:qti], :url => params[:qur])
later.save
end
respond_to do |format|
format.js { render :layout=>false }
end
end
Now return to the view. Each link has a 'div' with unique id='stock'. When user press the link I need to add text to specific div with corresponding id.
I have a stock.js.erb file:
$("#stock<number>").html("some text");
How can I pass div-id to stock.js.erb and how can I use it ?
Common use is to add object.id to your DOM id. That what you exactly did:
<div id="<%= "stock_#{q.question_id}" %>"></div>
Then in your controller you shoud define your question_id or your exact question:
def stock
if(!Later.where(:question_id => params[:qid]).exists?)
later = Later.new(:question_id => params[:qid], :name => params[:qti], :url => params[:qur])
later.save
end
#question_id = params[:qid]
end
Now it will be shared with your stock.js.erb file:
$("#stock_<%= #question_id %>").html("some text");

Resources