How to translate find_by_sql statement into named_scope? - sql

How do I translate the following into a named_scope?
def self.commentors(cutoff=0)
return User.find_by_sql("select users.*, count(*) as total_comments from users, comments
where (users.id = comments.user_id) and (comments.public_comment = 1) and (comments.aasm_state = 'posted') and (comments.talkboard_user_id is null)
group by users.id having total_comments > #{cutoff} order by total_comments desc")
end
Here's what I have right now but it doesn't seem to work:
named_scope :commentors, lambda { |count=0|
{ :select => "users.*, count(*) as total_comments",
:joins => :comments,
:conditions => { :comments => { :public_comment => 1, :aasm_state => 'posted', :talkboard_user_id => nil} },
:group => "users.id",
:having => "total_comments > #{count.to_i}",
:order => "total_comments desc"
}
}
Ulimately, this is what worked;
named_scope :commentors, lambda { |*args|
{ :select => 'users.*, count(*) as total_comments',
:joins => :comments,
:conditions => { :comments => { :public_comment => 1, :aasm_state => 'posted', :talkboard_user_id => nil} },
:group => 'users.id',
:having => ['total_comments > ?', args.first || 0],
:order => 'total_comments desc' }
}

The problem you have is because you replaced selecting from users, comments with an inner join with comments. To properly translate the SQL to a named_scope, use this:
named_scope :commentors, lambda { |cutoff|
{ :select => 'users.*, count(*) as total_comments',
:conditions => { :comments => { :public_comment => 1, :aasm_state => 'posted', :talkboard_user_id => nil } },
:from => 'users, comments',
:group => 'users.id',
:having => ['total_comments > ?', cutoff],
:order => 'total_comments desc' } }
And you can't have a default value for lambda parameters, so you can't use |cutoff = 0|.

Related

Thinking Sphinx Scope Returning mix of Results and "blanks"

Controller:
#sites = Site.inspections_enabled_controllers_search.search("test")
#sites.each do |s|
if s == nil
puts "WHAT THE ...?"
end
ap s #print out the site
end
Model:
has_many :inspections_enabled_controllers,
:class_name => 'Controller',
:conditions => ['controllers.inspections_enabled = ?', true]
sphinx_scope(:inspections_enabled_controllers_search) {
{
:joins => :inspections_enabled_controllers
}
}
Returns:
#<Site:0x000000114618b8> {
:id => 156,
:name => "Test Site"
}
WHAT THE ...?
nil
WHAT THE ...?
nil
WHAT THE ...?
nil
#<Site:0x000000111c41a0> {
:id => 213,
:name => "TestRail V1.5 - SmartLine"
}
WHAT THE ...?
nil
WHAT THE ...?
nil
WHAT THE ...?
nil
WHAT THE ...?
nil
#<Site:0x00000011461200> {
:id => 220,
:name => "Activation Testing"
}
NOTICE the total of SEVEN "-" which are simply empty items in an array.
This worked for me
#sites = Site.inspections_enabled_controllers_search.search("test", :retry_stale => 1)
Reference:
http://pat.github.com/ts/en/searching.html#nils

Access all nodes in neo4j

On rails console i am trying to call
#invoice = Invoice.all
which returns me some object like
<Neo4j::Traversal::Traverser:0x817382>
but when i tried to loop over the object like
#invoice.each { |t| p t.number }
i got nil,but database contains data for invoice.
Invoice class
class Invoice < Searchable
include Neo4jrb::Paperclip
include LinkableEntity
include HeadsupNotify
enable_optimistic_locking
before_destroy :verify_links, :prepend => true
before_destroy :destroy_invoice_items
property :number, :type => :string
property :currency, :default => Money.default_currency.to_s
property :date, :pay_by_date, :type => :date
property :purchase_order_number
property :settle, :default => false
property :link_1, :link_2, :type => :string
index :number, :type => :fulltext
domain_property :details
money_property :total_cost, :receivable_amount
attr_protected :total_cost, :receivable_amount
attr_accessor :delink_receipt
validates :total_cost, :numericality => {:greater_than_or_equal_to => 0}
validates :receivable_amount, :numericality => {:greater_than_or_equal_to => 0}
validates :date,:number, :customer_id, :event_id, :project_id, :department_id,
:brand_id, :premise_id, :user_id, :currency, :presence => true
validates :link_1, :length => { :maximum => 250 }
validates :link_2, :length => { :maximum => 250 }
validate :number_uniqueness
validate :invoice_items_present
validate :invoice_items_currency
validate :issue_credit_notes_valid
validate :pay_by_date_valid, :unless => "date.nil?"
validate :check_not_linked, :on => :update
has_one(:event).from(Event, :invoices_for_event)
has_one(:project).from(Project, :invoices_for_project)
has_one(:department).from(Department, :invoices_for_department)
has_one(:brand).from(Brand, :invoices_for_brand)
has_one(:premise).from(Premise, :invoices_for_premise)
has_one(:user).to(User)
has_one(:customer).from(Customer, :invoices_for_customer)
alias :party :customer
has_n(:invoice_items).to(InvoiceItem)
has_n(:receipts).from(Receipt, :paid_invoices)
has_n(:issue_credit_notes).from(IssueCreditNote, :credit_notes_for_invoice)
has_one(:invoices_for_settle).to(Settle)
links :receipts, :issue_credit_notes,:invoices_for_settle
has_neo4jrb_attached_file :photo
{:customer => :name, :event => :name, :department => :name, :project => :name, :brand => :name,
:premise => :name, :user => :email}.each do |target, method|
delegate method, :to => target, :prefix => true, :allow_nil => true
end
accepts_id_for :customer, :event, :project, :department, :brand, :premise, :user
accepts_nested_attributes_for :invoice_items, :allow_destroy => true
validates_associated :invoice_items
validates :customer_name, :presence => true, :length => { :maximum => 100 }
validates :event_name, :presence => true, :length => { :maximum => 100 }
validates :premise_name, :presence => true, :length => { :maximum => 100 }
validates :project_name, :presence => true, :length => { :maximum => 100 }
validates :brand_name, :presence => true, :length => { :maximum => 100 }
validates :department_name, :presence => true, :length => { :maximum => 100 }
validates :link_1, :length => { :maximum => 250 }
validates :link_2, :length => { :maximum => 250 }
after_validation :set_total_cost
serialize :methods => :invoice_items
before_validation :delink
Can anyone please help me with this?
Thanks in advance.
I'm not exactly sure of how to do this with Ruby On Rails, but if your Invoice objects (nodes) are in a lucene full text index, you could use a Cypher query to return all Invoices.
Something like:
START invoices=node:Invoices('name: *') RETURN invoices;

elasticsearch geo_distance query give me error how to write geo_distance query?

I have a table, schools with the fields: id, name, address, city, state, zip, latitude and longitude.
I want to search for schools within 12km by giving latitude and longitude; I am using this query but it's not working.
curl -X GET "http://localhost:9200/schools/school/_search?=true" -d '{"filter" : {"geo_distance" : {"distance" :"12km", "location": "40,-70"}}}'
I get the following error:
{
"error":"SearchPhaseExecutionException[
Failed to execute phase [query], total failure;
shardFailures {[_na_][schools][0]: No active shards}{[_na_][schools][1]:
No active shards}{[_na_][schools][2]: No active shards}{[_na_][schools][4]:
No active shards}{[WJV55VsxQU-XW8VPmXImwA][schools][3]:
RemoteTransportException[[Archie Corrigan][inet[/192.168.1.109:9300]][search/phase/query]]; nested:
SearchParseException[[schools][3]: from[-1],size[-1]: Parse Failure [Failed to parse source [
{\"filter\" :
{\"geo_distance\" :
{\"distance\" :\"12km\", \"location\": \"40,-70\"}
}
}]
]
]; nested: QueryParsingException[[schools] failed to find geo_point field [location]];}]",
"status":500
}
model configuration in rails
# ElasticSearch integration
include Tire::Model::Callbacks
include Tire::Model::Search
include Search::ReloadHelper
tire do
settings({
:analysis => {
:filter => Search::Filters.hs_name_filters,
:analyzer => Search::Analyzers.hs_name_analyzers
}
})
mapping do
indexes :id, :type => 'integer', :index => :not_analyzed
indexes :name, :type => 'string', :analyzer => :hs_name_analyzer
indexes :address, :type => 'string', :index => :not_analyzed
indexes :city, :type => 'string', :analyzer => :hs_name_analyzer
indexes :state, :type => 'string', :index => :not_analyzed
indexes :zip, :type => 'integer', :index => :not_analyzed
indexes :location, :type => 'geo_point', :lat_lon => true
end
end
def to_indexed_json
{
:id => id,
:name => name,
:address => address,
:city => city,
:state => state,
:zip => zip,
:location => {
:lat => latitude,
:lon => longitude
}
}.to_json
end
How can I get this to work?

Netzke basepack. Need advice with multi uploading fields

Is there any easy way to include the multiupload feature to NetzkeFormView or GridView(AddInForm)?
My current image uloading field with carrierwave is:
{:name => :image_link, :xtype => :displayfield, :display_only => true, :getter => lambda { |r| %Q(<a href='#{r.image.url}'>Download</a>) if r.image.url }},
{:name => :image, :field_label => "Upload image", :xtype => :fileuploadfield, :getter => lambda { |r| "" }, :display_only => true}

How to DRY up routes in Rails 3

In Rails 3, given routes like
get 'about/terms', :as => 'terms'
get 'about/privacy', :as => 'privacy'
get 'about/jobs', :as => 'career'
get 'about/feedback', :as => 'feedback'
get 'about/contact', :as => 'contact'
get 'about/us', :as => 'about'
How to DRY it up?
Recon something like this would do it:
['terms', 'privacy', 'jobs', 'feedback', 'contact' ,'us'].each { |r|
get "about/#{r}", :as => r
}
if about is a controller or you hava a controller for your static pages
['terms', 'privacy', 'jobs', 'feedback', 'contact' ,'us'].each { |r|
get "/#{r}", :controller => 'about', :action => r
}