How to hold the checkbox true value in rails after search - ruby-on-rails

The search is working fine but the problem is that when i print the excel report according to the result.it is showing all the values in the database, filter is not working then Checkbox true values are gone. How to hold the 'All address' checkbox params after refreshing the page.
This is my view
.col-md-3.small_scale_margin-top2
= check_box_tag "all_address"
= label_tag "Show All Addresses"
This is my controller
if params[:search].present? or params[:excel_report].present?
search_customer_supplier = params[:search_customer_supplier]
if params[:organization_children].present? and search_customer_supplier["id"].present?
organization_id = search_customer_supplier["id"]
organization = Organization.find(organization_id)
anchestor_ids = organization.anchestors.map{|o| o[:member].id }
search_customer_supplier["id"] = "(#{anchestor_ids.join(' OR ')})" if anchestor_ids.any?
end
#puts "======================================================================"
# puts params[:search_customer_supplier]['accounts_dealer_types.dealer_code']
params[:search_customer_supplier]['accounts_dealer_types.dealer_code'] = params[:search_customer_supplier]['accounts_dealer_types.dealer_code'].join(" OR ") if params[:search_customer_supplier]['accounts_dealer_types.dealer_code'].present?
# puts params[:search_customer_supplier]['accounts_dealer_types.dealer_code']
customer_report = params[:search_customer_supplier].map { |k, v| "#{k}:#{v}" if v.present? }.compact
else
customer_report = ["accounts_dealer_types.dealer_code:(CUS OR SUP OR INDCUS OR INDSUP)"]
end
#all_address = params[:all_address].to_bool if params[:all_address].present?
refined_query += customer_report.join(" AND ")
params[:query] = refined_query
# params[:per_page] = 500
#customer_reports = Organization.search(params)
puts "========================================================="
puts #customer_reports
puts "========================================================="
#account_managers = User.where(active: true)
respond_to do |format|
if params[:excel_report].present?
request.format = "xls"
format.xls { set_attachment_name "customer_supplier_report.xls" }
else
format.html
end
end
end
In my controller this is the relevant part for the checkbox
#all_address = params[:all_address].to_bool if params[:all_address].present?

Just use #all_address to set the checked attribute of check_box_tag
= check_box_tag "all_address", "1", #all_address
Note: Because the checked attribute is the third attribute in the list, you must provide a second attribute too. The "1" is just the default that would be used for the second argument anyway.

Related

How to hold the true value of many checkboxes at once after page refresh

The search is working fine.but my problem is When i checked one checkbox and searched,It will get my results and also checkbox true state also exist after the refresh.But when checking two or more checkboxes it doesn't hold the true states.I need to hold those true states
My problem is i have 4 checkboxes. when i checkd two or more checkboxes at once, it will get my results and then true states are gone.I need to hold these states to print the report after the page refresh.
This is my current view of four checkboxes.
.row
.col-md-3
= check_box_tag "search_customer_supplier[accounts_dealer_types.dealer_code][]","CUS", params[:search_customer_supplier]['accounts_dealer_types.dealer_code'] == 'CUS'
= label_tag "Organizational Customer"
.col-md-3
= check_box_tag "search_customer_supplier[accounts_dealer_types.dealer_code][]", "SUP", params[:search_customer_supplier]['accounts_dealer_types.dealer_code'] == 'SUP'
= label_tag "Organzational Supplier"
col-md-3
= check_box_tag "search_customer_supplier[accounts_dealer_types.dealer_code][]", "INDCUS", params[:search_customer_supplier]['accounts_dealer_types.dealer_code'] == 'INDCUS'
= label_tag "Individual Customer"
.col-md-3
= check_box_tag "search_customer_supplier[accounts_dealer_types.dealer_code][]", "INDSUP", params[:search_customer_supplier]['accounts_dealer_types.dealer_code'] == 'INDSUP'
= label_tag "Individual Supplier"
This is my controller
def customer_supplier_report
Organization
Address
ContactNumber
refined_query = ""
if params[:search].present? or params[:excel_report].present?
search_customer_supplier = params[:search_customer_supplier]
if params[:organization_children].present? and search_customer_supplier["id"].present?
organization_id = search_customer_supplier["id"]
organization = Organization.find(organization_id)
anchestor_ids = organization.anchestors.map{|o| o[:member].id }
search_customer_supplier["id"] = "(#{anchestor_ids.join(' OR ')})" if anchestor_ids.any?
end
#puts "======================================================================"
# puts params[:search_customer_supplier]['accounts_dealer_types.dealer_code']
params[:search_customer_supplier]['accounts_dealer_types.dealer_code'] = params[:search_customer_supplier]['accounts_dealer_types.dealer_code'].join(" OR ") if params[:search_customer_supplier]['accounts_dealer_types.dealer_code'].present?
puts params[:search_customer_supplier]['accounts_dealer_types.dealer_code']
customer_report = params[:search_customer_supplier].map { |k, v| "#{k}:#{v}" if v.present? }.compact
else
customer_report = ["accounts_dealer_types.dealer_code:(CUS OR SUP OR INDCUS OR INDSUP)"]
end
#all_address = params[:all_address].to_bool if params[:all_address].present?
refined_query += customer_report.join(" AND ")
params[:query] = refined_query
params[:per_page] = 4000
#customer_reports = Organization.search(params)
#account_managers = User.where(active: true)
respond_to do |format|
if params[:excel_report].present?
request.format = "xls"
format.xls { set_attachment_name "customer_supplier_report.xls" }
else
format.html
end
end
end
Field name search_customer_supplier[accounts_dealer_types.dealer_code][] means that params[:search_customer_supplier]['accounts_dealer_types.dealer_code'] is an array, so you should check it for inclusion:
check_box_tag "search_customer_supplier[accounts_dealer_types.dealer_code][]",
"CUS",
params.dig(:search_customer_supplier, 'accounts_dealer_types.dealer_code')&.include?('CUS')

How to write a conditions when a value from drop down is selected with select_tag?

I am trying to generate a report where there are 3 static values in a drop down, where when we select one value and click on submit, the code of this value has to be generated.
This is my reports controller:
def create_report
#report = MyReport.create_report(params[:id], params.merge(account: current_account, user: current_user))
#report.execute
end
In app/views/reports/report/_report.html.haml:
= content_for :report_filters do
.form-group
= select_tag :param_name, options_for_select([['A data', 'A'], ['B data', 'B']], params[:param_name])
This is my .rb file in app/reports folder:
class TransactionReport < MyReport
def execute
#items = []
if params[:param_name] == "A"
daily_items = A.by_account(#account).active.includes(:company_name, :emp_name, :address).where('date(txn_date) = ? ', current_date)
#items << Item.new(items: daily_items, date: current_date) unless daily_items.empty?
elsif params[:param_name] == "B"
daily_items = B.by_account(#account).active.includes(:company_name, :emp_name, :primary_sales_rep).where('date(txn_date) = ? ', current_date)
end
end
end
It displaying error as:
undefined local variable or method `params' for #
Please tell me how to write if sattement if A is selected or B or C without using Javascript..

Export to excel using csv library

I have the following code to export to excel
on my controller:
def users_report
#users = Kid.where(confirmation_token: nil).paginate(:page => params[:page], :per_page => 30)
#userxls = Kid.where(confirmation_token: nil)
respond_to do |format|
format.html
format.xls { send_data #userxls.to_csv({col_sep: "\t"}) }
end
end
on my model:
def self.to_csv(options = {})
CSV.generate(options) do |csv|
csv << ["Name", "Surname", "E-mail", "Birthday", "School", "Class", "Native Language", "Practised Language", "Conversations same Native", "Convserations different Native", "Message same Native", "Message different Native", "Posts", "Videos watched", "Clossed/Finished calls", "Missed calls", "Connections per Week", "Nb of foreign friends", "Nb of friends same country", "Activation Date", "Email Parent", "Parent Activated"]
all.each do |kid|
kids = Array.new
kid.name = kid.name rescue "No name"
kid.surname = kid.surname rescue "No surname"
kid.email = kid.email rescue "No email"
kid.birthday = kid.birthday rescue "No age"
kid.school.name = kid.school.name rescue "No School"
kid.courses.first.name = kid.courses.first.name rescue "No Course"
kid.native_languages = kid.native_languages rescue "No native language"
kid.practice_languages = kid.practice_languages rescue "No practise language"
kid.number_of_native_conversations = kid.number_of_native_conversations rescue "0"
kid.number_of_foreign_conversations = kid.number_of_foreign_conversations rescue "0"
kid.number_of_native_messages = kid.number_of_native_messages rescue "0"
kid.number_of_foreign_messages = kid.number_of_foreign_messages rescue "0"
kid.number_of_activity_posts = kid.number_of_activity_posts rescue "0"
kid.number_of_finished_closed_calls = kid.number_of_finished_closed_calls rescue "0"
kid.number_of_missed_calls = kid.number_of_missed_calls rescue "0"
kid.avg_of_connections_week = kid.avg_of_connections_week rescue "0"
kid.number_of_foreign_friends = kid.number_of_foreign_friends rescue "0"
kid.number_of_friends_same_country = kid.number_of_friends_same_country rescue "0"
kid.confirmed_at = kid.confirmed_at.try(:strftime, "%d/%m/%Y")
kid.tutor.email = kid.tutor.email rescue 'No parent email'
kid.tutor.confirmed = kid.tutor.confirmed rescue 'No parent email'
kids << [kid.name, kid.surname, kid.email, kid.birthday, kid.school.name, kid.courses.first.name, kid.native_languages, kid.practice_languages, kid.number_of_native_conversations, kid.number_of_foreign_conversations, kid.number_of_native_messages, kid.number_of_foreign_messages, kid.number_of_activity_posts, kid.number_of_finished_closed_calls, kid.number_of_missed_calls, kid.avg_of_connections_week, kid.number_of_foreign_friends, kid.number_of_friends_same_country, kid.confirmed_at.try(:strftime, "%d/%m/%Y"), kid.tutor.email, kid.tutor.confirmed? ]
kids.each do |k|
csv << k
end
end
end
end
I know this code is horrible, but I getting the following problem:
1) I can insert electments directo on my csv array, because when I open the file I get something like #kid<3248293028>, instead of name, surname, email, bla bla bla, this I why I have to insert first on a kids array and then using a each, insert in the csv array.
2)Inside my model I have several methods, like age, to get the age of the kids:
def age
now = Time.now.utc.to_date
(now.year - self.birthday.year - (self.birthday.to_date.change(:year => now.year) > now ? 1 : 0)) rescue (now.year - self.birthday.year)
end
but the t0_csv method does not see this method, I have the same problem with other methods like:
sentence_native_languages_of
sentence_practise_languages_of
number_of_native_conversations
number_of_foreign_conversations
number_of_native_messages
etc etc etc, all of then exist in the model but the to_csv never see this methods.
Why, help me to understand.
Thanks in advance.
UPDATE
here is one of the method that my to_csv method can't see
def number_of_native_conversations
na_messages = 0
KidConversation.all_for(self).each do |conversation|
na_messages += 1 unless conversation.foreign_conversation_for? self
end
return na_messages
end

Ruby on Rails filter array using three fields

I am trying to search through my model using 3 columns. Also if the column is empty, it is valid. This is how I am doing it
def getactivityfortoday
#temp = params[:temp]
logger.debug "params temp:#{#temp.inspect}"
#sky = params[:sky]
#day = params[:day]
#todaysactivities = []
#activities=[]
#finaldata = []
#activities = Weatherclockactivity.all
#attemptactivities = []
#attemptactivities = #user.attempts
for activity in #activities do
logger.debug "activity: #{activity.attributes.inspect}"
if #temp.to_i < activity.temperatureMax.to_i && #temp.to_i > activity.temperatuureMin.to_i
if #sky == activity.sky || activity.sky == ""
if #day == activity.day
#todaysactivities << activity
end
end
end
end
for activity in #todaysactivities
for attempt in #attemptactivities
if attempt == activity
finaldata << {activity: activity, attempt: "yes"}
else
finaldata << {activity: activity, attempt: "no"}
end
end
end
respond_to do |format|
format.html { render action: "new" }
format.json { render json: #finaldata }
end
The response I get is an empty array but I should be getting 3 rows as a response.
spelling mistake here
activity.temperatuureMin.to_i
And
finaldata << {activity: activity, attempt: "yes"}
should be
#finaldata << {activity: activity, attempt: "yes"}
Also you could be more concise
def getactivityfortoday
#temp = params[:temp]
logger.debug "params temp:#{#temp.inspect}"
#sky = params[:sky]
#day = params[:day]
#activities = Weatherclockactivity.all
#attemptactivities = #user.attempts
#finaldata = #activities.map do |activity|
if (activity.temperatureMin.to_i + 1...activity.temperatureMax.to_i).include?(#temp.to_i) && ( #sky == activity.sky || activity.sky == "") && #day
#attemptactivities.include?(activity) ? {activity: activity, attempt: "yes"} : {activity: activity, attempt: "no"}
end
end.compact
respond_to do |format|
format.html { render action: "new" }
format.json { render json: #finaldata }
end
end
How about something like this?
I tried to make it a balance of readability and conciseness. First we filter for the desired activities. Then we structure the output. This should be easier to debug.
def getactivityfortoday
#temp = params[:temp].to_i
#sky = params[:sky]
#day = params[:day]
#activities = Weatherclockactivity.all
#attemptactivities = #user.attempts
selected_activities = #activities.select do |activity|
# Make sure it's the right temperaure
return false unless (activity.temperatureMin.to_i + 1 ... activity.temperatureMax.to_i).include? #temp
# Make sure the sky matches, or the sky is blank
return false unless (#sky.blank? || #sky.activity == activity.sky)
# Make sure the day matches
return false unless #day == activity.day
# Otherwise, it's good!
return true
end
selected_attempted_activities = selected_activities.map do|activity|
ret = {activity: activity}
ret[:attempt] = #attemptactivities.include?(activity) ? "yes" : "no"
ret
end
respond_to do |format|
format.html { render action: "new" }
format.json { render json: selected_attempted_activities }
end
end
There are a few typos in your original (for instance, #finaldata not finaldata). Make sure that you spell instance variables (things starting with #, like #sky) correctly, since if you try to access an undefined instance variable, it'll silently default to nil.
The best and flexible way is to use ActiveModel::Model
It allows you to use many more useful methods.
it will seems like:
app/models/activity_report.rb
Class ActivityReport
include ActiveModel::Model
attr_accessor :day, :activity # and etc.
validates :day, presence: true
def day
#day.to_s # for example
end
def day=(value)
#day = value - 1.month # for example every date which user set will set on one month ago
end
# and etc
end
app/controllers/posts_controller.rb
...
def index
#activity = ActivityReport.new(params[:activity])
end
def create
#activity.create!
end
...
app/views/posts/index.html.haml
= form_for #activity do |f|
= f.day
For more information you could take a look at:
http://edgeapi.rubyonrails.org/classes/ActiveModel/Model.html
http://railscasts.com/episodes/219-active-model (old)
http://railscasts.com/episodes/416-form-objects (newer, but a little complex)

Map field value in ruby

I have such class-array:
#types = Type.where("TYP_MOD_ID = ?", params[:mod_id])
There are i have field TYP_KV_FUEL_DES_ID which is number....
But how can i via map method change this value via method?
I have tried something like:
def get_types_for_mod2
#types = Type.where("TYP_MOD_ID = ?", params[:mod_id])
#types.map { |e| e.TYP_KV_FUEL_DES_ID = get_via_designation(e.TYP_KV_FUEL_DES_ID) }
respond_to do |format|
format.json { render :json => #types}
end
end
def get_via_designation(id)
designation = Designation.find_by_DES_ID(id)
destext = DesText.find_by_TEX_ID(designation.DES_TEX_ID)
destext.TEX_TEXT
end
So how can i change value of e.TYP_KV_FUEL_DES_ID ?
upd1:
i don't need to commit anything! just for json i fetch data and change for view some field! no db!
#types = Type.where("TYP_MOD_ID = ?", params[:mod_id]).map do |type|
type.TYP_KV_FUEL_DES_ID = get_via_designation(type.TYP_KV_FUEL_DES_ID)
type
end
here we will map over the result from the query Type.where("TYP_MOD_ID = ?", params[:mod_id]) and set the TYP_KV_FUEL_DES_ID to the return from get_via_designation
UPDATE: added that the map block will return "type"

Resources