Debugging Database Query with NameError uninitialized constant - ruby-on-rails
I have the below query in my Ruby on rail site. I am new to Ruby on Rails and tring teach myself this coding. It is alot different the php that i know.
The originial line that i edited was: (But i need it to pull from a different table.)
Module.const_get(self.search_type.capitalize).where(where).select(select).limit(limit).order(order).page(page).per_page(10)
My question is How do i intiate the Following Constant variable. or reprogram it to work?
I am recieving the following Error:
Started GET "/searches/23795" for 50.83.98.168 at 2014-04-24 22:00:54 -0500
2014-04-24 22:00:54 INFO -- Processing by SearchesController#show as HTML
2014-04-24 22:00:54 INFO -- Parameters: {"id"=>"23795"}
2014-04-24 22:01:01 INFO -- Completed 500 Internal Server Error in 6716ms
2014-04-24 22:01:01 FATAL --
NameError (uninitialized constant Search::Hotloads):
app/models/search.rb:62:in `search'
app/controllers/searches_controller.rb:41:in `show'
Our database table name is "hotloads"
def searches(page)
where = []
where << PrepareSearch.states("dest", self.dest_states) unless self.dest_states.blank?
where << PrepareSearch.date('created_at', self.date_posted, '>=') unless self.date_posted.blank?
if self.search_type == 'load'
select = "loads.id, origin, dest, pickup, delivery, ltl, equipment_id, weight, length, rate"
where << PrepareSearch.attribute('ltl', self.ltl, '=') unless self.ltl.blank?
elsif self.search_type == 'truck'
select = "trucks.id, origin, dest, available, expiration, equipment_id, comments"
where << PrepareSearch.date('available',self.available,self.available_operator) unless self.available.blank?
self.expiration.blank?
end
where << "covered=false AND deleted=false"
where = where.join(' AND ')
order = self.order_by ? self.order_by + " desc" : ""
limit = "LIMIT=200"
Hotloads.where(where).select(select).limit(limit).order(order).page(page).per_page(5)
end
UPDATE
if i change this line to this
Module.Hotloads.where(where).select(select).limit(limit).order(order).page(page).per_page(5)
I get this error
Started GET "/searches/23795" for 50.83.98.168 at 2014-04-24 22:14:15 -0500
2014-04-24 22:14:16 INFO -- Processing by SearchesController#show as HTML
2014-04-24 22:14:16 INFO -- Parameters: {"id"=>"23795"}
2014-04-24 22:14:20 INFO -- Completed 500 Internal Server Error in 3913ms
2014-04-24 22:14:20 FATAL --
NoMethodError (undefined method `Hotloads' for Module:Class):
app/models/search.rb:94:in `searches'
app/controllers/searches_controller.rb:42:in `show'
Requested Controller
class SearchesController < ApplicationController
load_and_authorize_resource
attr_accessor :log
def new
#search = Search.new
end
def edit
#search = Search.find(params[:id])
#search.origin_cs = #search.origin.cs unless #search.origin.nil?
#search.dest_cs = #search.dest.cs unless #search.dest.nil?
%w[pickup delivery available expiration].each do |date|
date = date.to_sym
#search[date] = #search[date].strftime("%F") unless #search[date].blank?
end
end
def create
#search = Search.new(params[:search])
if #search.save
redirect_to #search
else
render 'new'
end
end
def update
#search = Search.find(params[:id])
if #search.update_attributes(params[:search])
redirect_to #search
else
render 'edit'
end
end
def show
#search = Search.find(params[:id])
#searches = Search.find(params[:id])
#results = #search.search(params[:page])
#resultss = #searches.searches(params[:page])
#search.update_attribute(:results, #results.count)
#searches.update_attribute(:resultss, #resultss.count)
respond_to do |format|
format.html
format.js {render "results"}
format.js {render "resultss"}
end
end
def load_search
#search = Search.new
#user_id = params[:user_id]
respond_to do |format|
format.html { raise "Unsupported" }
format.js
end
end
def truck_search
#search = Search.new
#user_id = params[:user_id]
respond_to do |format|
format.html { raise "Unsupported" }
format.js
end
end
def recent_search
#user_id = params[:user_id] || current_user.id
#searches = Search.includes(:origin, :dest).where(user_id: #user_id).limit(15).order("searches.updated_at desc")
respond_to do |format|
format.html { render "_recent_search", locals: {user_id: #user_id, searches: #searches} }
format.js
end
end
def saved_search
#user_id = params[:user_id] || current_user.id
#searches = Search.includes(:origin, :dest).where(user_id: #user_id, saved: true).order("searches.updated_at desc").page(params[:saved_search]).limit(15).per_page(15)
respond_to do |format|
format.html { render "_saved_search", locals: {user_id: #user_id, searches: #searches} }
format.js
end
end
def ezsearch
#user_id = params[:user_id]
respond_to do |format|
format.html { raise "Unsupported" }
format.js
end
end
def states
results = []
JSON(AUTOCOMPLETE_STATES).each {|state| results << state if (state["name"].downcase.include?(params[:q]) or state["id"].downcase.include?(params[:q]))}
respond_to do |format|
format.json { render json: (JSON.dump results)}
end
end
def convert
#search_params = Search.find(params[:search_id])
if #search_params.search_type == "truck"
redirect_to :controller => "trucks", :action => "new", :search_id => params[:search_id]
else
redirect_to :controller => "loads", :action => "new", :search_id => params[:search_id]
end
end
#log = Logger.new("#{Rails.root}/log/searches.log")
#log.datetime_format = "%F %T"
end
Search Model
class Search < ActiveRecord::Base
attr_accessible :available, :delivery, :dest, :length, :ltl, :origin, :pickup, :rate, :search_type, :user_id, :weight, :expiration, :pickup_operator, :delivery_operator, :expiration_operator, :available_operator, :length_operator, :rate_operator, :weight_operator, :origin_zip, :dest_zip, :origin_radius, :dest_radius, :saved, :date_posted, :order_by, :origin_cs, :results, :resultss, :dest_cs, :origin_states, :dest_states, :origin_id, :dest_id, :equipment_ids, :temp_origin, :temp_dest, :temp_equipment
attr_accessor :origin_cs, :dest_cs, :log
before_validation :convert_cs_to_id
OPERATORS = ["<=","<",">=",">","=","!="]
NUMERICALITY_MESSAGE = "Needs to be a number"
LOCATION_FORMAT_MESSAGE = "Location must be in format (city,ST)"
LOCATION_PRESENCE_MESSAGE = "Location does not exist"
validates_inclusion_of :pickup_operator, in: OPERATORS
validates_inclusion_of :delivery_operator, in: OPERATORS
validates_inclusion_of :expiration_operator, in: OPERATORS
validates_inclusion_of :available_operator, in: OPERATORS
validates_inclusion_of :length_operator, in: OPERATORS
validates_inclusion_of :rate_operator, in: OPERATORS
validates_inclusion_of :weight_operator, in: OPERATORS
validates_inclusion_of :search_type, in: ["load","truck"]
validates_numericality_of :rate, {allow_nil: true, message: NUMERICALITY_MESSAGE}
validates_numericality_of :origin_radius,{allow_nil: true, message: NUMERICALITY_MESSAGE}
validates_numericality_of :dest_radius, {allow_nil: true, message: NUMERICALITY_MESSAGE}
validates_numericality_of :weight, allow_nil: true, message: NUMERICALITY_MESSAGE
validates_numericality_of :length, allow_nil: true, message: NUMERICALITY_MESSAGE
validates_presence_of :search_type
validates_presence_of :origin_id, :if => :origin_cs?
validates_presence_of :dest_id, :if => :dest_cs?
belongs_to :user
has_and_belongs_to_many :equipment
belongs_to :origin, class_name: "Location", foreign_key: :origin_id
belongs_to :dest, class_name: "Location", foreign_key: :dest_id
def search(page)
where = []
where << PrepareSearch.states("dest", self.dest_states) unless self.dest_states.blank?
where << PrepareSearch.states("origin", self.origin_states) unless self.origin_states.blank?
where << PrepareSearch.location('origin', self.origin.coords, self.origin_radius) unless self.origin.blank?
where << PrepareSearch.location('origin', self.origin.coords, self.origin_radius) unless self.origin.blank?
where << PrepareSearch.zip('origin', self.origin_zip, self.origin_radius) unless self.origin || self.origin_zip.blank?
where << PrepareSearch.location('dest', self.dest.coords, self.dest_radius) unless self.dest.blank?
where << PrepareSearch.zip('dest', self.dest_zip, self.dest_radius) unless self.dest || self.dest_zip.blank?
where << PrepareSearch.equipment(self.equipment_ids) unless self.equipment_ids.blank?
where << PrepareSearch.date('created_at', self.date_posted, '>=') unless self.date_posted.blank?
if self.search_type == 'load'
select = "loads.id, origin, dest, pickup, delivery, ltl, equipment_id, weight, length, rate"
where << PrepareSearch.date('pickup', self.pickup, self.pickup_operator) unless self.pickup.blank?
where << PrepareSearch.date('delivery', self.delivery, self.delivery_operator) unless self.delivery.blank?
where << PrepareSearch.attribute('length', self.length, self.length_operator) unless self.length.blank?
where << PrepareSearch.attribute('rate', self.rate, self.rate_operator) unless self.rate.blank?
where << PrepareSearch.attribute('weight', self.weight, self.weight_operator) unless self.weight.blank?
where << PrepareSearch.attribute('ltl', self.ltl, '=') unless self.ltl.blank?
elsif self.search_type == 'truck'
select = "trucks.id, origin, dest, available, expiration, equipment_id, comments"
where << PrepareSearch.date('available',self.available,self.available_operator) unless self.available.blank?
where << PrepareSearch.date('expiration',self.expiration,self.expiration_operator) unless self.expiration.blank?
end
where << "covered=false AND deleted=false"
where = where.join(' AND ')
order = self.order_by ? self.order_by + " desc" : ""
limit = "LIMIT=200"
Module.const_get(self.search_type.capitalize).where(where).select(select).limit(limit).order(order).page(page).per_page(10)
end
def searches(page)
where = []
where << PrepareSearch.states("dest", self.dest_states) unless self.dest_states.blank?
where << PrepareSearch.states("origin", self.origin_states) unless self.origin_states.blank?
where << PrepareSearch.location('origin', self.origin.coords, self.origin_radius) unless self.origin.blank?
where << PrepareSearch.location('origin', self.origin.coords, self.origin_radius) unless self.origin.blank?
where << PrepareSearch.zip('origin', self.origin_zip, self.origin_radius) unless self.origin || self.origin_zip.blank?
where << PrepareSearch.location('dest', self.dest.coords, self.dest_radius) unless self.dest.blank?
where << PrepareSearch.zip('dest', self.dest_zip, self.dest_radius) unless self.dest || self.dest_zip.blank?
where << PrepareSearch.equipment(self.equipment_ids) unless self.equipment_ids.blank?
where << PrepareSearch.date('created_at', self.date_posted, '>=') unless self.date_posted.blank?
if self.search_type == 'load'
select = "loads.id, origin, dest, pickup, delivery, ltl, equipment_id, weight, length, rate"
where << PrepareSearch.date('pickup', self.pickup, self.pickup_operator) unless self.pickup.blank?
where << PrepareSearch.date('delivery', self.delivery, self.delivery_operator) unless self.delivery.blank?
where << PrepareSearch.attribute('length', self.length, self.length_operator) unless self.length.blank?
where << PrepareSearch.attribute('rate', self.rate, self.rate_operator) unless self.rate.blank?
where << PrepareSearch.attribute('weight', self.weight, self.weight_operator) unless self.weight.blank?
where << PrepareSearch.attribute('ltl', self.ltl, '=') unless self.ltl.blank?
elsif self.search_type == 'truck'
select = "trucks.id, origin, dest, available, expiration, equipment_id, comments"
where << PrepareSearch.date('available',self.available,self.available_operator) unless self.available.blank?
where << PrepareSearch.date('expiration',self.expiration,self.expiration_operator) unless self.expiration.blank?
end
where << "covered=false AND deleted=false"
where = where.join(' AND ')
order = self.order_by ? self.order_by + " desc" : ""
limit = "LIMIT=200"
Module.Hotloads.where(where).select(select).limit(limit).order(order).page(page).per_page(5)
end
module PrepareSearch
def PrepareSearch.equipment(equipments)
eq = ""
equipments.each {|e| eq += "'#{e}'," }
eq = eq[0..-2]
"equipment_id IN (#{eq})"
end
def PrepareSearch.attribute(attribute, value, comparison)
"#{attribute} #{comparison} #{value}"
end
def PrepareSearch.date(type, date, comparison)
if comparison == '='
"CAST(#{type} as TEXT) LIKE '%#{date.strftime("%F")}%'"
elsif comparison == '<='
"#{type} #{comparison} '#{date.strftime("%F")} 23:59:59'"
else
"#{type} #{comparison} '#{date.strftime("%F")}'"
end
end
def PrepareSearch.zip(type, zip, radius)
location = Location.where(zip: zip).first
if location
"(ST_Distance(#{type}, ST_GeographyFromText('POINT( #{location.coords.x} #{location.coords.y} )')) <= #{radius.to_f*1609.334})"
else
#if no locations match zip search for location that will never exist.
"(ST_Distance(#{type}, ST_GeographyFromText('POINT( 1 1 )')) <= #{radius.to_f*1609.334})"
end
end
def PrepareSearch.location(type, location, radius)
"(ST_Distance(#{type}, ST_GeographyFromText('POINT( #{location.x} #{location.y} )')) <= #{radius.to_f*1609.334})"
end
def PrepareSearch.states(type, states)
states = states.split(",")
st = ""
states.each {|s| st += "'#{s}'," }
st = st[0..-2]
"#{type}_state IN (#{st})"
end
end
#log = Logger.new("#{Rails.root}/log/searches.log")
#log.datetime_format = "%F %T"
private
def convert_cs_to_id
temp_origin = Location.where(cs: self.origin_cs.downcase) unless self.origin_cs.blank?
self.origin_id = temp_origin.blank? ? "" : temp_origin.first.id
temp_dest = Location.where(cs: self.dest_cs.downcase) unless self.dest_cs.blank?
self.dest_id = temp_dest.blank? ? "" : temp_dest.first.id
end
def origin_cs?
errors.add(:origin_cs, "not a valid location") if !origin_cs.blank? && origin_id.blank?
origin_cs.blank? ? false : true
end
def dest_cs?
errors.add(:dest_cs, "not a valid location") if !dest_cs.blank? && dest_id.blank?
dest_cs.blank? ? false : true
end
end
I think you should only do following while querying:
Hotloads.where(where).select(select).limit(limit).order(order).page(page).per_page(5)
as, what I guess, Module.const_get(self.search_type.capitalize) must be returning you the active record model to search, and on a separate note as par ActiveRecord conventions if your database table name is hotloads, than corresponding class name will be Hotload, so in that case, your query will be like: Hotload.where(where).select(select)...
Related
i have code which implement upload song to database using plupload-jquery and show in datatable for management but song not saved to database
uploaded_song_datatable.rb --which is used for showing list of song in datatable. class UploadedSongDatatable < AjaxDatatablesRails::Base include AjaxDatatablesRails::Extensions::Kaminari def_delegator :#view, :best_in_place def_delegator :#view, :link_to def_delegator :#view, :uploaded_song_path def_delegator :#view, :autocomplete_album_name_albums_path def_delegator :#view, :autocomplete_artist_name_artists_path def_delegator :#view, :autocomplete_genre_name_genres_path def_delegator :#view, :year_list def_delegator :#view, :content_tag def_delegator :#view, :image_tag def sortable_columns #sortable_columns ||= [ 'UploadedSong.title', 'UploadedSong.artist', 'UploadedSong.album', 'UploadedSong.genre' ] end def searchable_columns #searchable_columns ||= [ 'UploadedSong.title', 'UploadedSong.artist', 'UploadedSong.album', 'UploadedSong.genre' ] end private def data records.map do |record| [ # best_in_place(record, , :as => :checkbox, :collection => ['<input name="mark[]" type="checkbox">'.html_safe, '<input type="checkbox" checked="true">'.html_safe]), nil, "<input type='checkbox' class='checkBoxClass' name=\"songids[]\" value='#{record.id}' >", best_in_place(record, :is_explicit, :as => :checkbox, :collection => ['<input type="checkbox">'.html_safe, '<input type="checkbox" checked="true">'.html_safe] , url: uploaded_song_path(record, field_to_update: 'is_explicit')), best_in_place(record, :title, :display_with => lambda { |v| v.blank? ? "( No title )" : v }, url: uploaded_song_path(record, field_to_update: 'title')), best_in_place(record, :artist, :display_with => lambda { |v| v.blank? ? "( No artist )" : v }, url: uploaded_song_path(record, field_to_update: 'artist'), html_attrs: { "data-autocomplete" => autocomplete_artist_name_artists_path, "object_id" => record.id.to_s }), best_in_place(record, :album, :display_with => lambda { |v| v.blank? ? "( No album )" : v }, url: uploaded_song_path(record, field_to_update: 'album'), html_attrs: { "data-autocomplete" => autocomplete_album_name_albums_path }), best_in_place(record, :genre, :display_with => lambda { |v| v.blank? ? "( No genre )" : v }, url: uploaded_song_path(record, field_to_update: 'genre'), html_attrs: { "data-autocomplete" => autocomplete_genre_name_genres_path }), best_in_place(record, :year, :as => :select, :collection => year_list, :display_with => lambda { |v| v.blank? ? "( No year )" : v }, url: uploaded_song_path(record, field_to_update: 'year')), best_in_place(record, :track, :display_with => lambda { |v| v.blank? ? "( No track )" : v }, url: uploaded_song_path(record, field_to_update: 'track')), best_in_place(record, :comment, :display_with => lambda { |v| v.blank? ? "( No comment )" : v }, url: uploaded_song_path(record, field_to_update: 'comment')), if record.cover_id.blank? link_to("No Cover", "#cover_modal", data: {song_id: record.id, toggle: "modal", multiqueue: 'false'}) else link_to("#") do image_tag(record.cover.cover_pic.url, href: "#cover_modal", height: '50', width: '50', data: {song_id: record.id, toggle: "modal", src: record.cover.cover_pic.url, multiqueue: 'false'}) end end, link_to(uploaded_song_path(record), method: :delete, data: { confirm: "Are you sure to delete the song ?"}) do content_tag :span, '', class: "glyphicon glyphicon-trash glyphicon-red" end ] end end def get_raw_records UploadedSong.all end end uploaded_song_controller.rb require 'taglib' class UploadedSongsController < ApplicationController before_action :authenticate_user! authorize_resource respond_to :json, :html, :js def index if params[:from_modal] sleep(10) flash[:notice] = "Click 'Refresh', to view recently uploaded songs." end #songs = UploadedSong.count respond_to do |format| format.html format.json { render json: UploadedSongDatatable.new(view_context) } end end def new #song = UploadedSong.new end def create Rails.logger.debug params[:file] extraction_path = Pathname.new("#{Rails.root}/public") file_ext = File.extname(params[:file].original_filename) original_file_name = params[:file].original_filename tmp_file_base_name = File.basename(params[:file].path) uploaded_tmp_file = "#{extraction_path}/#{tmp_file_base_name}" uploaded_file = "#{extraction_path}/#{original_file_name}" if params[:file].content_type == "application/zip" Rails.logger.debug "moving #{params[:file].path} to #{extraction_path}" FileUtils.mv(params[:file].path, extraction_path) Rails.logger.debug "file moved" if File.rename(uploaded_tmp_file, uploaded_file) Resque.enqueue(ZipExtractor, uploaded_file, extraction_path.to_s, true, false) Rails.logger.debug "Background job started" head 200 else File.delete(uploaded_tmp_file) if File.exist?(uploaded_tmp_file) end elsif %w(.mp3 .ogg .mp4 .m4a).include?(file_ext) FileUtils.mv(params[:file].path, extraction_path) if File.rename(uploaded_tmp_file, uploaded_file) Rails.logger.info "renaming #{tmp_file_base_name} to #{original_file_name}" Resque.enqueue(ZipExtractor, false, uploaded_file, false, false) head 200 else File.delete(uploaded_tmp_file) if File.exist?(uploaded_tmp_file) head 200 end else File.delete(params[:file].path) if File.exist?(params[:file].path) head 200 end end def edit #song = UploadedSong.find(params[:id]) end def update #song = UploadedSong.find(params[:id]) #song.field_to_update = (params[:field_to_update]) if #song.update_attributes(uploaded_song_params) Resque.enqueue(ZipExtractor, #song.id, false, false, #song.field_to_update) end respond_with_bip #song end def destroy #song = UploadedSong.find(params[:id]) #song.destroy! unless #song.cover_id.blank? cover = Cover.find(#song.cover_id) cover.destroy! end if session[:ids] == nil respond_to do |format| format.html { redirect_to uploaded_songs_url, notice: 'Song was successfully destroyed.' } format.json { head :no_content } end else session[:ids].delete(#song.id) respond_to do |format| format.html { redirect_to uploaded_songs_url, notice: 'Song was successfully destroyed.' } format.json { head :no_content } end end end private def uploaded_song_params params.require(:uploaded_song).permit(:title, :artist, :album, :year, :track, :genre, :comment, :song_name, :attachment, :is_explicit) end def set_session_for_ids if session[:ids] == nil session[:ids] = Array.new end end def update_music_metadata?(song) TagLib::FileRef.open(song.attachment_url) do |fileref| unless fileref.null? tag = fileref.tag # true is for writing. tag.title = song.title tag.artist = song.artist tag.album = song.album tag.year = song.year.to_i tag.track = song.track.to_i tag.genre = song.genre tag.comment = song.comment if fileref.save return true else return false end end end end def update_song_name?(song) file_handle = File.open(song.song_path) dir_location = File.dirname(song.song_path) file_ext = File.extname(song.song_path) song_name = song.song_name + file_ext song_path = dir_location + "/#{song_name}" attachment = File.rename_file(file_handle, song_path) if song.update_attributes({attachment: attachment, song_name: song_name, song_path: song_path}) return true else return false end end end uploaded_song.rb require 'file_size_validator' class UploadedSong < ActiveRecord::Base belongs_to :cover mount_uploader :attachment, AttachmentUploader skip_callback :commit, :after, :remove_attachment!, if: Proc.new{ |s| s.file_keep == true } validates :attachment, :file_size => { less_than: 200.megabytes } attr_accessor :file_keep, :field_to_update end zip_extractor.rb require 'taglib' require 'zip' class ZipExtractor #queue = :songs_queue def self.perform path_to_zip, destination_path, delete = false, field_to_update if !path_to_zip.blank? and delete and !destination_path.blank? and !field_to_update unzip(path_to_zip, destination_path) Dir.glob("#{destination_path}" + '/*') do |music_file| base_file_name = File.basename(music_file) next if base_file_name.casecmp("__macosx") == 0 process_song(music_file) end end if !path_to_zip and !delete and !destination_path.blank? and !field_to_update process_song(destination_path) end if !path_to_zip.blank? and !delete and !destination_path and !field_to_update.blank? log("processing song details update") song = UploadedSong.find(path_to_zip) song_details = nil TagLib::FileRef.open(song.attachment_url) do |fileref| unless fileref.null? tag = fileref.tag case field_to_update.to_s when "title" tag.title = song.title when "artist" tag.artist = song.artist when "album" tag.album = song.album when "year" tag.year = song.year.to_i when "track" tag.track = song.track.to_i when "genre" tag.genre = song.genre when "comment" tag.comment = song.comment else log 'No parameters for "field_to_update".' end unless fileref.save TagLib::FileRef.open(song.attachment_url) do |fileref| unless fileref.null? tag = fileref.tag song_details = { title: tag.title, artist: tag.artist, album: tag.album, year: tag.year, track: tag.track, genre: tag.genre, comment: tag.comment, is_explicit: false } end end if song_details[:title].downcase.include? 'explicit' song_details[:is_explicit] = true end song.update_attributes(song_details) end end end end end def self.process_song(destination_path) if %w(.mp3 .ogg .mp4 .m4a).include? File.extname(destination_path) if %w(.ogg .mp4 .m4a).include? File.extname(destination_path) destination_path = convert_video_to_audio(destination_path) end if %w(.mp3).include? File.extname(destination_path) process_mp3(destination_path) else delete_file(destination_path) end else delete_file(destination_path) end end def self.process_mp3(destination_path) song_details = extract_metadata(destination_path) rename_file = File.dirname(destination_path) + "/1-----" + File.basename(destination_path) extension = File.extname(destination_path) cover_file_name = nil rename = File.rename(destination_path, rename_file) if rename == 0 transcoded_movie, cover_file_name = transcode_file(rename_file, destination_path) if transcoded_movie.valid? delete_file(rename_file) song_details[:attachment] = File.open(destination_path) if File.exist?(destination_path) # cover = nil p song_details[:attachment] unless cover_file_name.nil? cover = Cover.new({name: File.basename(cover_file_name), cover_pic: File.open(cover_file_name)}) if File.exist?(cover_file_name) end song = UploadedSong.new(song_details) if !cover.blank? if cover.save delete_file(cover_file_name) song.cover_id = cover.id if song.save delete_file(destination_path) end end else p 9999999999999999999999999999999999999999999999999999 p song.valid? p song.save p song.errors.any? p song.errors.full_messages p 9999999999999999999999999999999999999999999999999999 if song.save! delete_file(destination_path) end end else delete_file(destination_path) delete_file(rename_file) end else delete_file(destination_path) end end def self.convert_video_to_audio(destination_path) log "Found video file. Converting video to audio." movie = FFMPEG::Movie.new(destination_path) if movie.valid? file_name_with_no_ext = File.basename(destination_path, "#{File.extname(destination_path)}") out_file = "#{File.dirname(destination_path)}/#{file_name_with_no_ext}.mp3" out_movie = movie.transcode(out_file) if out_movie.valid? delete_file(destination_path) destination_path = out_file end end return destination_path end def self.extract_metadata(destination_path) log("extracting metadata from media file") song_details = nil TagLib::FileRef.open(destination_path) do |fileref| unless fileref.null? tag = fileref.tag song_details = { title: tag.title.blank? ? 'Single' : tag.title, artist: tag.artist.blank? ? 'Single' : tag.artist, album: tag.album.blank? ? 'Single' : tag.album, year: tag.year.blank? ? '' : tag.year, track: tag.track.blank? ? '' : tag.track, genre: tag.genre.blank? ? '' : tag.genre, comment: tag.comment.blank? ? '' : tag.comment, is_explicit: false } if song_details[:title].downcase.include? 'explicit' song_details[:is_explicit] = true end if tag.title.blank? tag.title = "Single" fileref.save elsif tag.artist.blank? tag.artist = "Single" fileref.save elsif tag.album.blank? tag.album = "Single" fileref.save end end end return song_details end def self.transcode_file(rename_file, destination_path) movie = FFMPEG::Movie.new(rename_file) cover_file_name = nil transcoded_movie = nil p movie.valid? if movie.valid? log "ffmpeg validates file #{rename_file}" if movie.video_stream == nil options = {audio_codec: "libmp3lame", audio_bitrate: 320, audio_sample_rate: 44100, audio_channels: 2} else log "removing video stream from file and extracting cover" cover_file_name = extract_image_from_file(rename_file) # "-vn" flag is used to remove video_stream from mp3 file options = {audio_codec: "libmp3lame", audio_bitrate: 320, audio_sample_rate: 44100, audio_channels: 2, custom: "-vn"} end transcoded_movie = movie.transcode(destination_path, options) else log "Unable to process media file." delete_file(rename_file) end return transcoded_movie, cover_file_name end def self.extract_image_from_file(rename_file) cover_file_name = nil cover_path = "#{Rails.root}/public/covers/" TagLib::MPEG::File.open(rename_file) do |fileref| cover_tag = fileref.id3v2_tag cover_img = cover_tag.frame_list('APIC').first unless cover_img.blank? ext = cover_img.mime_type.rpartition('/')[2] o = [('a'..'i'), ('A'..'Z')].map { |i| i.to_a }.flatten rand_string = (1..18).map { o[rand(o.length)] }.join cover_file_name = "#{cover_path}#{File.basename(rename_file).chomp('.mp3').gsub('1-----','')}-#{rand_string}.#{ext}" File.open(cover_file_name, "wb") { |f| f.write cover_img.picture } log "cover extracted from media file." end end return cover_file_name end def self.delete_file(filename) File.delete(filename) if File.exist?(filename) end def self.log(message) Rails.logger.debug "\n*********** #{message} ***************" end def self.unzip(path_to_zip, destination_path) log "unzipping #{path_to_zip} \nto #{destination_path}" Zip::File.open(path_to_zip) do |zip_file| # log "zip file is #{zip_file}" zip_file.each do |f| f_path=File.join(destination_path, f.name) FileUtils.mkdir_p(File.dirname(f_path)) a = zip_file.extract(f, f_path) unless File.exist?(f_path) # log "file extraction complete" # log a end log "after zip file loop" end # log "removing original zip file" FileUtils.rm(path_to_zip) # log "removed zip file from #{path_to_zip}" end end in above means zip_extractor.rb I checked song.valid? it gives me false in rails 6 and error is cover must exist and I have checked cover is nil but in rails 4 it gives true and also checked in this version also cover is nil but song saved in database in rails but not in rails 6. anyone have proper reason why it behave like this answer fast otherwise mailto: santu.essence#gmail.com
RAILS: db count is always 0 in spec
Here is a simple case of spec in Rails 4.2: it "returns redirect to Save & Copy" do user_access = FactoryGirl.create(:user_access, :action => 'create', :resource =>'simple_orderx_orders', :role_definition_id => #role.id, :rank => 1, :sql_code => "") session[:user_id] = #u.id q1 = FactoryGirl.create(:simple_orderx_order) q = FactoryGirl.attributes_for(:simple_orderx_order) FactoryGirl.create(:project_misc_definitionx_misc_definition, :resource_id => q1.id, :resource_string => 'simple_orderx_orders', definition_category: 'production_step') expect { get 'create', {:order => q, commit: I18n.t('Save & Copy')} expect(response).to redirect_to URI.escape(SUBURI + "/view_handler?index=0&msg=Successfully Saved!") }.to change(ProjectMiscDefinitionx::MiscDefinition.all.reload, :count).by(1) end end In debugger, there is a new record being added to table MiscDefinition and MiscDefinition.all.count is 2, but in spec the ProjectMiscDefinitinox::MiscDefinition.all.count is always 0 and the spec case fails. What could cause the counting error in spec? Here is the create in controller: def create #order = SimpleOrderx::Order.new(new_params) #order.last_updated_by_id = session[:user_id] #order.entered_by_id = session[:user_id] #order.fort_token = session[:fort_token] copy_steps(#order) if params[:commit] == I18n.t('Save & Copy') #copy mfg steps from previous order if #order.save copy_steps(#order.reload) if params[:commit] == I18n.t('Save & Copy') #copy mfg steps from previous order redirect_to URI.escape(SUBURI + "/view_handler?index=0&msg=Successfully Saved!") else #erb_code = find_config_const('order_new_view', session[:fort_token], 'simple_orderx') flash[:notice] = t('Data Error. Not Saved!') render 'new' end end def copy_steps(order) obj = Order.where('drawing_num = ? AND id != ?', order.drawing_num, order.id).order('created_at DESC') if order.drawing_num.present? #find the previous order of the same drawing# obj = Order.where('part_num = ? AND id != ?', order.part_num, order.id).order('created_at DESC') if obj.blank? && order.part_num.present? obj = Order.where('part_name Like ? AND id != ?', "%#{order.part_name}%", order.id).order('created_at DESC') if obj.blank? && order.part_name.present? copied = false obj.limit(4).each do |o| SimpleOrderx.production_step_class.where('resource_id = ? AND resource_string = ? AND definition_category = ?', o.id, params[:controller].sub('/', '_'), 'production_step').each do |r| new_step = SimpleOrderx.production_step_class.new() new_step = r.dup new_step.resource_id = order.id begin new_step.save copied = true rescue => e flash[:notice] = 'Error in copying production steps: ' + e.message end end return if copied end if obj.present? end
Parameter missing error(rails)
I am facing an error that when ever I try to call the function finalized_request it throws me an error saying "param is missing or the value is empty: finalizedeal". Since I am new to this I can't figure out what am I doing wrong(I am new to ROR). Request_controller.rb class RequestsController < ApplicationController before_action :set_request, only: [:show, :edit, :update, :destroy] # GET /requests # GET /requests.json def index #categories_list = Category.getAll() end def active user = session[:user] #requests = Array.new #tag = Array.new #requests = Request.getRequestByUser(user) #requests.each.with_index do |request, index| if request != nil #tag[index] = Array.new request[:tag_id].each do |t| #tag[index] << Tag.getTag(t) end end end end # GET /requests/1 # GET /requests/1.json def show #user = User.getUser(#request[:user_id]) #tag = Array.new #request[:tag_id].each do |cate| #tag << Tag.getTag(cate) end end # GET /requests/1/edit def edit #tag = Array.new #request[:tag_id].each do |cate| #tag << Tag.getTag(cate) end end # POST /requests def post_request tags_arr = params[:tags] ; #=begin #categories = Array.new ; #if tags != nil # tags.each do |tag| # category = Category.createCategoryIfNotExist(tag) # if(category != nil) # categories << category[:_id] # end # end #end #=end tags = Array.new ; if tags_arr != nil tags_arr.each do |t| tag = Tag.createTagIfNotExist(t) if(tag != nil) tags << tag[:_id] end end end request_data = request_params user_id = session[:user] request_data[:tag_id] = tags request_data[:user_id] = user_id #request_ = Request.createRequest(request_data) if #request_ flash[:notice] = "Request Post successfully." redirect_to :action => "active" end end # PATCH/PUT /requests/1 # PATCH/PUT /requests/1.json def update #tags = params[:tags] ; #categories = Array.new ; #if tags != nil # tags.each do |tag| # category = Category.createCategoryIfNotExist(tag) # if(category != nil) # categories << category[:_id] # end # end #end tags_arr = params[:tags] ; tags = Array.new ; if tags_arr != nil tags_arr.each do |t| tag = Tag.createTagIfNotExist(t) if(tag != nil) tags << tag[:_id] end end end Rails.logger.info("RequestsParams: #{request_params.inspect}") request_data = request_params if request_data[:is_service] != "on" request_data[:is_service] = "off" end user_id = session[:user] request_data[:tag_id] = tags request_data[:user_id] = user_id if Request.updateRequest(#request,request_data) flash[:notice] = "Request has been Edited successfully." redirect_to :action => "active" end end def delete_request () if Request.delete_request(params[:id]) flash[:notice] = "Request has been Deleted successfully." render :json => "great" end end # GET /requests def finalize_request() finalizedrequest = finalizedRequest_params request = Request.getRequest(finalizedrequest[:title]) finalizedrequest[:title] = request[:title] Request.delete_request(request[:_id]) FinalizedDeal.createFinalizedRequest(finalizedrequest) redirect_to :action => "bookmark" end # GET /requests def bookmark user = session[:user] #requests = Array.new #tag = Array.new #requests = Request.getRequestByUser(user) #requests.each.with_index do |request, index| if request != nil #tag[index] = Array.new request[:tag_id].each do |t| #tag[index] << Tag.getTag(t) end end end end # GET /requests def bookmark_request data = params[:d] bookmarked_against_Request = Request.getRequest(1) request_bookmarked = Request.getRequest(data) request_bookmarked_2 = request_bookmarked bookmarked_against_Request_2 = bookmarked_against_Request Rails.logger.info("Bookmark 2: #{bookmarked_against_Request_2.inspect}") #bookmarked_against_Request_2[:favourites] << request_bookmarked[:id] #request_bookmarked_2[:favourites_of] << bookmarked_against_Request[:id] #hello #Request.updateRequest(request_bookmarked , request_bookmarked_2) #Request.updateRequest(bookmarked_against_Request , bookmarked_against_Request_2) redirect_to :action => "bookmark" end private # Use callbacks to share common setup or constraints between actions. def set_request #request = Request.getRequest(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def request_params params.require(:request).permit(:title, :description, :type , :is_service , :required_user_location , :required_product_location ,:Upper_price_range , :lower_price_range , :negotiable , :type , :tags , :category_id) end def finalizedRequest_params params.require(:finalizedeal).permit(:title , :description) end end finalized_deal.rb class FinalizeDeal include Mongoid::Document field :deal_details, type: String field :categories, type: Array field :owner_user, type: MongoId field :corsponing_user, type: MongoId field :title, type: String field :corresponding_product, type: String field :meeting_date, type: String field :date_finalized, type: String field :description, type: String class << self def getRequestByUser(user_id) requests = where(user_id: user_id).to_a if requests requests end end def getFinzlizedRequest(req) request = find(req) if request request end end def createFinalizedRequest(req_data) request = self.new(req_data) if request.save request end end def updateFinalizedRequest(request,req_data) if request.update(req_data) request end end def delete_FinalizedRequest(req_id) if find(req_id).delete true end end end end request.html.erb div id="form-details-modal-lbms" class="reveal-modal" data-reveal> <h3>Enter Contract Details:</h3> <!--<form>--> <%= form_tag({controller: "requests", action: "finalize_request"}, method: "GET",id:"post-form-lbms" ,data: {abide: ''}) %> <input type="hidden" id="currect_opened_req_id" value="" name="FinalizeDeal[title]"/> <select name="meeting-id"> <option value="1">Meeting 1</option> <option value="2">Meeting 2</option> </select> <label for="details-lbms">Details</label> <textarea id="details-lbms" name="FinalizeDeal[description]"></textarea> <button class="button tiny"> Submit </button> </form> <a class="close-reveal-modal">×</a> </div> Please tell me what am I doing wrong. I am also posting a link to the screenshot of the error http://tinypic.com/r/n6t8w2/8 http://tinypic.com/r/33kdq1k/8
The code is complaining because you are requiring the :finalizedeal parameter (but apparently you are not passing it along) by adding this .require(:finalizedeal) to this code: def finalizedRequest_params params.require(:finalizedeal).permit(:title , :description) end So one solution would be to simply remove the require part. Like so: params.permit(:title , :description) #require source Ensures that a parameter is present.
If current time is 1 or more days earlier than starts_at
I have an exam starts_at field, and what I want to do is, if current date is 1 day or more before exam starts_at I want to redirect to somewhere else. And if current date is the same day as when the exam starts_at I want to redirect to the exam page....for now I just want to get the if statement correct, I will put the redirect later. Here is my controller. Student Session Controller class StudentSessionsController < ApplicationController before_action :set_student_session before_filter :config_opentok, except: :update before_action :try_authenticate_user!, except: :mobile before_action :check_compatability, except: :mobile def show #session = #student_session.session #session_id = #session.session_id #token = #opentok.generate_token #session_id, :data => "#{#student_session.id}" # If Time.now is 1 or more days before exam starts_at show message if (#session.exam.starts_at =< Time.now) render :text => "OK" else render :text => "Not ok" end if #student_session.student.present? #UserMailer.mobile_link(current_user.email, current_user.name, #student_session).deliver else #UserMailer.mobile_link(#student_session.email, #student_session.email, #student_session).deliver end ua = UserAgent.parse(request.user_agent) #student_session.operating_system = ua.os #student_session.browser = ua.browser #student_session.browser_version = ua.version.to_s #student_session.save render layout: "application_no_header" end def mobile #session = #student_session.session #session_id = #session.session_id #token = #opentok.generate_token #session_id, :data => "#{#student_session.id}_mobile" render layout: false end def update respond_to do |format| if #student_session.update(student_session_params) format.js end end end private # Use callbacks to share common setup or constraints between actions. def set_student_session #student_session = StudentSession.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def student_session_params params.require(:student_session).permit(:session_status, :publisher_status, :proctor_status, :mobile_status) end def config_opentok #opentok ||= OpenTok::OpenTok.new APP_CONFIG['opentok']['api_key'], APP_CONFIG['opentok']['secret'] end def try_authenticate_user! if #student_session.student.present? authenticate_user! end end def check_compatability user_agent = UserAgent.parse(request.user_agent) # http://tokbox.com/opentok/requirements/ unless (user_agent.browser == 'Chrome' and user_agent.version.to_a.first >= 23) or (user_agent.browser == 'Firefox' and user_agent.version.to_a.first >= 22) redirect_to '/browser' end end end
I'd suggest you use: if #session.exam.starts_at.to_date == Date.today # go to exam elsif #session.exam.starts_at.to_date < Date.today # go to place before the exam else # go to place after the exam end
As you're using rails you can do if (Time.now >= (#session.exam.starts_at - 1.day) ) render :text => "OK" else render :text => "Not ok" end
if ((#session.exam.starts_at - Time.now).to_i / 1.day) >= 1 render :text => "OK" else render :text => "Not ok" 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)