I am facing the below error after I removed two fields middle_name, last_name from the Student migration thru another migration. below are the errors.
Searchlogic::NamedScopes::OrConditions::UnknownConditionError in StudentController#advanced_search
The condition 'last_name' is not a valid condition, we could not find any scopes that match this.
RAILS_ROOT: /root/ansipro342
Application Trace | Framework Trace | Full Trace
/root/ansipro342/vendor/plugins/searchlogic/lib/searchlogic/named_scopes/or_conditions.rb:96:in `interpolate_or_conditions'
/root/ansipro342/vendor/plugins/searchlogic/lib/searchlogic/named_scopes/or_conditions.rb:75:in `each'
/root/ansipro342/vendor/plugins/searchlogic/lib/searchlogic/named_scopes/or_conditions.rb:75:in `interpolate_or_conditions'
/root/ansipro342/vendor/plugins/searchlogic/lib/searchlogic/named_scopes/or_conditions.rb:36:in `or_conditions'
/root/ansipro342/vendor/plugins/searchlogic/lib/searchlogic/named_scopes/or_conditions.rb:19:in `or_condition?'
/root/ansipro342/vendor/plugins/searchlogic/lib/searchlogic/named_scopes/or_conditions.rb:10:in `condition?'
/root/ansipro342/vendor/plugins/searchlogic/lib/searchlogic/search/scopes.rb:10:in `scope?'
/root/ansipro342/vendor/plugins/searchlogic/lib/searchlogic/search/method_missing.rb:16:in `method_missing'
/root/ansipro342/vendor/plugins/searchlogic/lib/searchlogic/search/conditions.rb:19:in `send'
/root/ansipro342/vendor/plugins/searchlogic/lib/searchlogic/search/conditions.rb:19:in `conditions='
/root/ansipro342/vendor/plugins/searchlogic/lib/searchlogic/search/conditions.rb:15:in `each'
/root/ansipro342/vendor/plugins/searchlogic/lib/searchlogic/search/conditions.rb:15:in `conditions='
/root/ansipro342/vendor/plugins/searchlogic/lib/searchlogic/search/date_parts.rb:19:in `conditions='
/root/ansipro342/vendor/plugins/searchlogic/lib/searchlogic/search/base.rb:18:in `initialize'
/root/ansipro342/vendor/plugins/searchlogic/lib/searchlogic/search/implementation.rb:10:in `new'
/root/ansipro342/vendor/plugins/searchlogic/lib/searchlogic/search/implementation.rb:10:in `search'
/root/ansipro342/app/controllers/student_controller.rb:816:in `advanced_search'
Request
Parameters:
{"search"=>{"order"=>"",
"first_name_or_middle_name_or_last_name_or_admission_no_like"=>"Imran"},
"commit"=>"Search"}
Following is the code area from Student controller where line 816 exists
def advanced_search
#search = Student.search(params[:search])
unless params[:search].present?
#batches = Batch.all
else
if params[:search].present?
#students = Array.new
if params[:advv_search].present? and params[:advv_search][:course_id].present?
unless params[:search][:batch_id_equals].present?
params[:search][:batch_id_in] = Batch.find_all_by_course_id(params[:advv_search][:course_id]).collect{|b|b.id}
end
end
if params[:search][:is_active_equals]=="true"
#students = Student.ascend_by_first_name.search(params[:search]).paginate(:page => params[:page],:per_page => 30)
elsif params[:search][:is_active_equals]=="false"
#students = ArchivedStudent.ascend_by_first_name.search(params[:search]).paginate(:page => params[:page],:per_page => 30)
else
#students = [{:student => {:search_options => params[:search], :order => :first_name}},{:archived_student => {:search_options => params[:search], :order => :first_name}}].model_paginate(:page => params[:page],:per_page => 30)#.sort!{|m, n| m.first_name.capitalize <=> n.first_name.capitalize}
end
#searched_for = ''
#searched_for += "<span>#{t('name')}/#{t('admission_no')}: " + params[:search][:first_name_or_admission_no_like].to_s + "</span>" if params[:search][:first_name_or_admission_no_like].present?
#searched_for += "<span>#{t('name')}: " + params[:search][:first_name_like].to_s + "</span>" if params[:search][:first_name_like].present?
#searched_for += " <span>#{t('admission_no')}: " + params[:search][:admission_no_equals].to_s + "</span>" if params[:search][:admission_no_equals].present?
if params[:advv_search].present? and params[:advv_search][:course_id].present?
course = Course.find(params[:advv_search][:course_id])
batch = Batch.find(params[:search][:batch_id_equals]) unless (params[:search][:batch_id_equals]).blank?
#searched_for += "<span>#{t('course_text')}: " + course.full_name + "</span>"
#searched_for += "<span>#{t('batch')}: " + batch.full_name + "</span>" if batch.present?
end
Please help I dont know where the last_name exists that its showing in error, I am very new to ruby on rails nd need this importantly.
Thanks in advance.
Thanks for the replies, The problem solved.
The problem was in the index migration, actually I removed the columns from the create migration but it was already there in index migration.
Dude that code is huge and very unlikely that someone will understand it by reading it one time..
Install rubocop or some other lint tool and clean that mess.
Related
I'm working on something to scrape real estate data from a certain website. It works as a standalone .rb file while saving to a JSON file. But I want this to run on Heroku and save the data to MongoDB.
Problem:
I keep getting the following errors when running:
rake aborted!
SyntaxError: /Users/user/Dropbox/Development/Rails/booyah/lib/tasks/properties_for_sale.rake:35: syntax error, unexpected tLABEL
street_name: #street_name,
^
/Users/user/Dropbox/Development/Rails/booyah/lib/tasks/properties_for_sale.rake:41: syntax error, unexpected tLABEL, expecting '='
bedrooms: #rooms[1],
^
/Users/user/Dropbox/Development/Rails/booyah/lib/tasks/properties_for_sale.rake:42: syntax error, unexpected tLABEL, expecting '='
number_of_floors: #number_of_floors,
^
/Users/user/.rvm/gems/ruby-2.1.1/gems/railties-4.1.1/lib/rails/engine.rb:654:in `load'
/Users/user/.rvm/gems/ruby-2.1.1/gems/railties-4.1.1/lib/rails/engine.rb:654:in `block in run_tasks_blocks'
/Users/user/.rvm/gems/ruby-2.1.1/gems/railties-4.1.1/lib/rails/engine.rb:654:in `each'
/Users/user/.rvm/gems/ruby-2.1.1/gems/railties-4.1.1/lib/rails/engine.rb:654:in `run_tasks_blocks'
/Users/user/.rvm/gems/ruby-2.1.1/gems/railties-4.1.1/lib/rails/application.rb:362:in `run_tasks_blocks'
/Users/user/.rvm/gems/ruby-2.1.1/gems/railties-4.1.1/lib/rails/engine.rb:449:in `load_tasks'
/Users/user/Dropbox/Development/Rails/booyah/Rakefile:6:in `<top (required)>'
/Users/user/.rvm/gems/ruby-2.1.1/bin/ruby_executable_hooks:15:in `eval'
/Users/user/.rvm/gems/ruby-2.1.1/bin/ruby_executable_hooks:15:in `<main>'
This is the code I'm using:
require 'mechanize'
namespace :properties_for_sale do
desc "Scrape all properties currently for sale"
task :start => :environment do
a = Mechanize.new
#a2 = Mechanize.new
#i = 1
BASE_URL = 'http://www.funda.nl'
def scrape_objects_on_page(page)
objects_on_page = page.search('//*[contains(concat( " ", #class, " " ), concat( " ", "object-street", " " ))]')
objects_on_page.each do |object|
#a2.get(BASE_URL + object[:href] + 'kenmerken/') do |page_2|
break if page_2.title == '404 - Pagina niet gevonden'
#street_name = page_2.search('//*[#id="main"]/div[1]/div/div/div/h1').text.strip
#price = page_2.search('//*[#id="main"]/div[1]/div/div/div/p[2]/span/span').text.strip.gsub("€ ", "").gsub(".", "").to_i
#url = page_2.uri.to_s
#living_area = page_2.search('//*[#id="twwo13"]/td/span[1]').text.strip.gsub(" m²", "").to_i
#content = page_2.search('//*[#id="twih12"]/td/span[1]').text.strip.gsub(" m³", "").to_i
#rooms = page_2.search('//*[#id="aaka12"]/td/span[1]').text.strip.scan(/\d/).to_i
#number_of_floors = page_2.search('//*[#id="twva12"]/td/span[1]').text.strip.to_i
#year = page_2.search('//*[#id="boja12"]/td/span[1]').text.strip.to_i
#broker = page_2.search('//*[contains(concat( " ", #class, " " ), concat( " ", "rel-info", " " ))]//h3').text.strip
#city = page_2.search('//*[#id="nav-path"]/div/p[1]/span[4]/a/span').text.strip
#district = page_2.search('//*[#id="nav-path"]/div/p[1]/span[5]/a/span').text.strip
#province = page_2.search('//*[#id="nav-path"]/div/p[1]/span[3]/a/span').text.strip
#type_of_property = page_2.search('//*[#id="soap12"]/td/span[1] | //*[#id="sowo12"]/td/span[1] | //*[#id="twsp12"]/td/span[1]').text.strip
Property.create = (
street_name: #street_name,
price: #price,
url: #url,
living_area: #living_area,
content: #content,
rooms: #rooms[0],
bedrooms: #rooms[1],
number_of_floors: #number_of_floors,
year: #year,
broker: #broker,
city: #city,
district: #district,
province: #province,
type_of_property: #type_of_property
)
puts Property.last
end
end
end
loop do
a.get("http://www.funda.nl/koop/rotterdam/sorteer-datum-af/p#{#i}/") do |page|
#end = page.search('//h3').text == 'Geen koopwoningen gevonden die voldoen aan uw zoekopdracht' ? true : false
scrape_objects_on_page(page) unless #end == true
#i = #i + 1
end
break if #end
end
puts "==================================================================================="
puts "# Done scraping #{#i - 1} pages and collected #{#all_objects_array.length} objects."
puts "==================================================================================="
end
end
This is what my Property model looks like (MongoMapper):
class Property
include MongoMapper::Document
key :street_name, String
key :price, Integer
key :url, String
key :living_area, Integer
key :content, Integer
key :rooms, Integer
key :bedrooms, Integer
key :number_of_floors, Integer
key :year, Integer
key :broker, String
key :city, String
key :district, String
key :province, String
key :type_of_property, String
end
What am I doing wrong?
You have a typo. Remove the equal sign between Property.create and the parens. Like below:
Property.create(
street_name: #street_name,
price: #price,
url: #url,
living_area: #living_area,
content: #content,
rooms: #rooms[0],
bedrooms: #rooms[1],
number_of_floors: #number_of_floors,
year: #year,
broker: #broker,
city: #city,
district: #district,
province: #province,
type_of_property: #type_of_property
)
Also, it might be better to store the #create call in a variable instead of calling Property.last. That way, you don't have to issue another query.
I'm getting this error lately :
Completed 500 Internal Server Error in 7609ms
GoogleDrive::Error (Updating cell https://spreadsheets.google.com/feeds/.../od6/private/full/R1C1 has failed: Missing resource version ID)
I haven't change anything, it worked fine before.
Using: Rails 3, gem 'google_drive'
Code:
def google_report
session = GoogleDrive.login(current_user.gmail, ActiveSupport::MessageEncryptor.new(SECRET).decrypt(current_user.gmail_pass))
asin = params[:asin]
#i_all = Item.where(:user_id => current_user.id, :asin => asin, :domain => params[:domain]).order("created_at desc")
# + 9 hours cuz of server time
time = (Time.now + 9.hours).strftime("%Y-%m-%d %H:%M:%S")
session.create_spreadsheet(asin + " " + time)
ws = session.spreadsheet_by_title(asin + " " + time).worksheets[0]
ws[1, 1] = "商品名"
ws[1, 2] = "ASIN"
...
#i_all.try(:each_with_index) do |i, index|
ws[index+2, 1] = i.title
ws[index+2, 2] = i.asin
...
begin
ws.save()
rescue GoogleDrive::Error
ws.save()
next
end
end
ws.save()
end
I think the fix was to add a version
https://developers.google.com/google-apps/spreadsheets/#specifying_a_version
I think it was optional, but they made it required.
Updating the gem did the trick :)
From google_drive (0.3.7) to google_drive (0.3.9)
Can anyone help me. i want to integrate ccavenue in my project i used ccavenue code but i got some error "undefined method `id' for nil:NilClass" at orderID = #transaction.id.to_s.. this is my code.
In application.helper -->
def verifyChecksum( merchantID, orderID, amount, authDesc, workingKey, checksum)
String str = merchantID+"|"+orderID+"|"+amount+"|"+authDesc+"|"+workingKey
String newChecksum = Zlib::adler32(str).to_s
return (newChecksum.eql?(checksum)) ? true : false
end
def getChecksum( merchantID, orderID, amount, redirectUrl, workingKey)
String str = merchantID + "|" + orderID + "|" + amount + "|" + redirectUrl + "|" + workingKey;
return Zlib::adler32(str)
end
In Controller -->
def index
orderID = #transaction.id.to_s
amount = #transaction.total_amount.to_s
redirectURL = "http://www.dealbuddie.com/transactions/"+#transaction.id.to_s+"/ccavenue_redirect"
checksum = getChecksum(CCAVENUE_MERCHANT_ID, orderID, amount, redirectURL, CCAVENUE_WORKING_KEY)
#ccaRequest =
"Merchant_Id="+CCAVENUE_MERCHANT_ID+"&"+
"Amount="+amount+"&"+
"Order_Id="+orderID+"&"+
"Redirect_Url="+redirectURL+"&"+
"billing_cust_name="+current_user.name+"&"+
"billing_cust_address="+#transaction.address.street_address+"&"+
"billing_cust_country="+#transaction.address.country+"&"+
"billing_cust_tel="+#transaction.address.cell_phone+"&"+
"billing_cust_email="+current_user.email+"&"+
"billing_cust_state="+#transaction.address.state+"&"+
"delivery_cust_name="+current_user.name+"&"+
"delivery_cust_address="+#transaction.address.street_address+"&"+
"delivery_cust_country="+#transaction.address.country+"&"+
"delivery_cust_state="+#transaction.address.state+"&"+
"delivery_cust_tel="+#transaction.address.cell_phone+"&"+
"delivery_cust_notes="+"Note"+"&"+
"billing_cust_city="+#transaction.address.city+"&"+
"billing_zip_code="+#transaction.address.pincode.to_s+"&"+
"delivery_cust_city="+#transaction.address.city+"&"+
"delivery_zip_code="+#transaction.address.pincode.to_s+"&"+
"Checksum="+checksum.to_s
Dir.chdir("#{RAILS_ROOT}/public/jars/") do
#encRequest = %x[java -jar ccavutil.jar #{CCAVENUE_WORKING_KEY} "#{#ccaRequest}" enc]
end
end
and action in controller -->
def ccavenue_redirect
#encResponse = params[:encResponse]
#checksum = false
#authDesc = false
#p = nil
#ccaResponse = nil
if (params[:encResponse])
if #encResponse
Dir.chdir("#{RAILS_ROOT}/public/jars/") do
#ccaResponse = %x[java -jar ravi-ccavutil.jar #{CCAVENUE_WORKING_KEY} "#{#encResponse}" dec]
end
#p = Rack::Utils.parse_nested_query #ccaResponse
if (!#p.nil? && #p["Merchant_Id"] && #p["Order_Id"] && #p["Amount"] && #p["AuthDesc"] && #p["Checksum"])
#checksum = verifyChecksum(#p["Merchant_Id"], #p["Order_Id"], #p["Amount"], #p["AuthDesc"], CCAVENUE_WORKING_KEY, #p["Checksum"])
#authDesc = #p["AuthDesc"].eql?("Y") ? true : false
end
end
if #checksum && #authDesc
transaction = Transaction.find(#p["Order_Id"])
transaction.payment_confirmed = true
transaction.save!
message = current_buyer.user.name + "! Thank you for your order! It will soon be at your doorsteps!"
redirect_to root_path, :flash => {:success => message}
else
if !#authDesc
message = current_buyer.user.name + "! Your bank did not authorize the transaction. Please go to Settings > My Orders page, and click on 'Pay Now' button to finish your transaction"
redirect_to root_path, :flash => {:error => message}
else
message = current_buyer.user.name + "! Oops! There was some error in retrieving your transaction confirmation. Please drop us an email at dealbuddie#dealbuddie.com for order confirmation."
redirect_to root_path, :flash => {:error => message}
end
end
else
message = current_buyer.user.name + "! Oops! Something went wrong while processing your request. Please go to Settings > My Orders page, and click on 'Pay Now' button to finish your transaction."
redirect_to root_path, :flash => {:success => message}
end
end
I got error in this "undefined method `id' for nil:NilClass" at
orderID = #transaction.id.to_s
got help from this link --
http://dealbuddie.tumblr.com/post/56908130601/integrating-ccavenue-with-ruby-on-rails-site
please guide me how can i correct this code..
try this out:
by searching over rubytoolbox 2 gems got listed
1> active_merchant_ccavenue
2> ccavenue
out of these ccavenue seems to be good, try using it.
In my view I send an ajax request to get the device_ports of a particular device.
Previously I used
def get_device_ports
if params[:id] != ''
#device_ports = Device.find(params[:id]).device_ports.all(:order => 'id ASC')
output = '<option value="">Select Device Port...</option>'
#device_ports.each do |device_port|
output = output + '<option value="' + device_port.id.to_s + '">' + device_port.name + '</option>'
end
render :text => output
else
render :text => '0'
end
end
Which worked one but now having changed my query I get an error undefined method 'name' for [268, "test-1"]:Array with 268 and test-1 being the id and name of the first row of results.
This is my updated code:
def get_device_ports
if params[:id] != '' and params[:device_id] != ''
# #device_ports = Device.find(params[:id]).device_ports.all(:order => 'id ASC')
device_id = params[:device_id]
# Need a list of ports that aren't in use or are multiuse
#device_ports = ActiveRecord::Base.connection.execute('SELECT DISTINCT d.id, d.name FROM device_ports d LEFT OUTER JOIN circuits c ON c.physical_port_id = d.id WHERE (c.physical_port_id IS NULL AND d.device_id = ' + device_id + ') OR (d.multiuse = 1 AND d.device_id = ' + device_id + ') ORDER BY d.id ')
output = '<option value="">Select Device Port...</option>'
#device_ports.each do |device_port|
output = output + '<option value="' + device_port.id.to_s + '">' + device_port.name + '</option>'
end
render :text => output
else
render :text => '0'
end
end
I'm just not sure why I'm getting the error, I imagine it's something trivial but due to the amount of different NoMethodError questions it's hard to find an answer.
You are having this problem because you aren't using ActiveRecord as an ORM to wrap the object, but rather executing a query and working on the resulting series of arrays. I would recommend changing your query like so:
#device_ports = Device.find(device_id).device_ports.includes(:circuits).
where('device_ports.multiuse = 1 OR circuits.id IS NULL').
order('device_ports.id').distinct
If you absolutely want to avoid ActiveRecord, then don't use id and name, but rather treat each record as an array:
output << %Q{<option value="#{device_port.first}">#{device_port.last}</option>}
UPDATE
I just noticed that you're using RoR-2. Although more painful, you can still use an ActiveRecord query like so:
#device_ports = DevicePort.all(
:joins => "LEFT JOIN circuits c ON device_ports.id = c.devic_port_id",
:conditions => ['device_ports.device_id = ? AND (device_ports.multiuse = 1 OR c.id IS NULL)', device_id],
:order => 'device_ports.id',
:select => 'DISTINCT device_ports.id, device_ports.name')
I have a model that looks like this:
class StopWord < ActiveRecord::Base
UPDATE_KEYWORDS_BATCH_SIZE = 1000
before_save :update_keywords
def update_keywords
offset = 0
max_id = ((max_kw = Keyword.first(:order => 'id DESC')) and max_kw.id) || 0
while offset <= max_id
begin
conditions = ['id >= ? AND id < ? AND language = ? AND keyword RLIKE ?',
offset, offset + UPDATE_KEYWORDS_BATCH_SIZE, language]
# Clear keywords that matched the old stop word
if #changed_attributes and (old_stop_word = #changed_attributes['stop_word']) and not #new_record
Keyword.update_all 'stopword = 0', conditions + [old_stop_word]
end
Keyword.update_all 'stopword = 1', conditions + [stop_word]
rescue Exception => e
logger.error "Skipping batch of #{UPDATE_KEYWORDS_BATCH_SIZE} keywords at offset #{offset}"
logger.error "#{e.message}: #{e.backtrace.join "\n "}"
ensure
offset += UPDATE_KEYWORDS_BATCH_SIZE
end
end
end
end
This works just fine, as the unit tests show:
class KeywordStopWordTest < ActiveSupport::TestCase
def test_stop_word_applied_on_create
kw = Factory.create :keyword, :keyword => 'foo bar baz', :language => 'en'
assert !kw.stopword, 'keyword is not a stop word by default'
sw = Factory.create :stop_word, :stop_word => kw.keyword.split(' ')[1], :language => kw.language
kw.reload
assert kw.stopword, 'keyword is a stop word'
end
def test_stop_word_applied_on_save
kw = Factory.create :keyword, :keyword => 'foo bar baz', :language => 'en', :stopword => true
sw = Factory.create :keyword_stop_word, :stop_word => kw.keyword.split(' ')[1], :language => kw.language
sw.stop_word = 'blah'
sw.save
kw.reload
assert !kw.stopword, 'keyword is not a stop word'
end
end
But mucking with the #changed_attributes instance variable just feels wrong. Is there a standard Rails-y way to get the old value of an attribute that is being modified on a save?
Update: Thanks to Douglas F Shearer and Simone Carletti (who apparently prefers Murphy's to Guinness), I have a cleaner solution:
def update_keywords
offset = 0
max_id = ((max_kw = Keyword.first(:order => 'id DESC')) and max_kw.id) || 0
while offset <= max_id
begin
conditions = ['id >= ? AND id < ? AND language = ? AND keyword RLIKE ?',
offset, offset + UPDATE_KEYWORDS_BATCH_SIZE, language]
# Clear keywords that matched the old stop word
if stop_word_changed? and not #new_record
Keyword.update_all 'stopword = 0', conditions + [stop_word_was]
end
Keyword.update_all 'stopword = 1', conditions + [stop_word]
rescue StandardError => e
logger.error "Skipping batch of #{UPDATE_KEYWORDS_BATCH_SIZE} keywords at offset #{offset}"
logger.error "#{e.message}: #{e.backtrace.join "\n "}"
ensure
offset += UPDATE_KEYWORDS_BATCH_SIZE
end
end
end
Thanks, guys!
You want ActiveModel::Dirty.
Examples:
person = Person.find_by_name('Uncle Bob')
person.changed? # => false
person.name = 'Bob'
person.changed? # => true
person.name_changed? # => true
person.name_was # => 'Uncle Bob'
person.name_change # => ['Uncle Bob', 'Bob']
Full documentation: http://api.rubyonrails.org/classes/ActiveModel/Dirty.html
You're using the right feature but the wrong API.
You should #changes and #changed?.
See this article and the official API.
Two additional notes about your code:
Never rescue Exception directly when you actually want to rescue execution errors. This is Java-style. You should rescue StandardError instead because lower errors are normally compilation error or system error.
You don't need the begin block in this case.
def update_keywords
...
rescue => e
...
ensure
...
end