i got this call in my controller:
#tournaments = Tournament.unignored.all(
:include => [:matches,:sport,:category],
:conditions=> ["matches.status in (0,4)
&& matches.date < ?",
Time.now.end_of_week + 1.day],
:order => "sports.sort ASC, categories.sort ASC, tournaments.sort ASC")
All works out in production mode and in the development console as well. But when I try to browse to that certain page in development mode i get:
The error occurred while evaluating nil.each
When I paste the created SQL Query into MySQL Browser there are results.
It refers to mysql2 (0.2.11) lib/active_record/connection_adapters/mysql2_adapter.rb:587:in `select'
The query arrives correctly in this one.
Did anyone had similar problems? This error came out of nowhere. No updates etc...
Thanks!
Rails 3.0.9 MySql 5.5 Ruby 1.8.7 and mysql2 0.2.11 gem
It looks like you need to use :joins instead of :include.
the :include option to all (and find and where etc) tells rails to separately do a query to load all the ncessary data for the given associated records.
The :join option gets rails to perform an SQL query that JOIN`s the associated models so you can query on their fields.
If you want to both query on the fields and preload them into the associations, you need to do both:
#tournaments = Tournament.unignored.all(
:include => [:matches,:sport,:category],
:joins => [:matches,:sport,:category],
:conditions=> ["matches.status in (0,4)
&& matches.date < ?",
Time.now.end_of_week + 1.day],
:order => "sports.sort ASC, categories.sort ASC, tournaments.sort ASC")
Related
I have these models:
teacher
class Teacher < ActiveRecord::Base
has_many :days
end
day
class Day < ActiveRecord::Base
belongs_to :teacher
end
And running these query:
active_teachers = Teacher.joins(:days).where("teacher.id" => found_teachers.pluck(:teacher_id).uniq, "days.day_name" => selected_day)
What the query (should) does: found_teachers is an array of all teachers with duplications, remove the duplicity and chose only those teachers that have classes on a respective day (selected_day contains a string, Monday for example).
Because the amount of data in the variable active_teachers is so big that I can't manually go record by record (and I am not sure that I built this query properly and it does exactly what I need), I am trying to find out how is this query translated to SQL from ActiveRecord.
Usually I see everything in the terminal where is running server for the Rails app, but as of now, I don't see there this query stated.
So the question is, how can I see how the ActiveRecord query is translated to SQL?
Thank you in advance.
To get details from a query you're typing, you can do:
query.to_sql
query.explain
You can use
ActiveRecord::Base.logger = Logger.new STDOUT
and run your query in rails console. So it prints out the sql queries in the console
We just updated our Rails App from 3.0.13 to 3.2.6 and have encountered a minor problem when using the .where method of the Active Record Query Interface with mysql2.
What used to work before:
client = Client.first
User.where(:client => client)
now leads to:
ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column
'users.client' in 'where clause': SELECT users.* FROM users WHERE
users.client = 1
But when explicitly using the column name of the foreign key, it seems to work just fine:
client = Client.first
User.where(:client_id => client.id)
#=> Relation of users with the given client_id
The associations have not changed (users belong to client, client has many users). This now seems to be the problem with every association of this kind.
Do we now really have to change all these where queries so that they use the foreign_key or is there any other way?
rails version:
gem "rails", "~> 3.2.6"
mysql2 version:
gem "mysql2", "~> 0.3.11"
We just found out that this functionality was provided by a gem called meta_where, which is deprecated in Rails 3.1+.
There is an alternative, squeel, which unfortunately doesn't provide the exact same syntax. (Or we just haven't found out yet...)
Investigating now...
Thanks #zsquare for pointing out.
While setting up Sphinx on my production server, this strange error came up when trying to index
ERROR: index 'benefit_core': sql_range_query: You have an error in your SQL
syntax; check the manual that corresponds to your MySQL server version for the
right syntax to use near '' at line 1
This doesn't happen on my local machine. And yes, that is an empty string.
Does anyone seen this type of issue before?
benefit.rb
define_index do
# Fields
indexes category
indexes title
indexes tags
indexes description
indexes brief_description
indexes brand
indexes short_description
indexes long_description
indexes benefit_description
indexes address.city
indexes address.state
indexes address.street_1
where sanitize_sql(["active = true and expiration > ?", Time.now])
set_property :field_weights => {
:title => 15,
:tags => 10,
:brand => 10,
:description => 3
}
end
Thinking-Sphinx - 1.4.4
Sphinx - 0.9.9
Thank you!
Be sure you are running the most recent version of Thinking Sphinx, 3.0.4 or so. Looks like there has been some issues with sanitize_sql
https://github.com/freelancing-god/thinking-sphinx/issues/213
Also try re-writing the line to be
where sanitize_sql(["active = ? and expiration > ?", true, Time.now])
Also try commenting out all the lines and gradually add them back to determine exactly where the error is occurring.
The problem ended up being with the sanitize_sql method. I replaced that line with:
where "active = true AND expiration > \"#{Time.now.to_formatted_s(:db)}\""
Thanks for the help!
I'm trying to seed about 100,000 users using rake db:seed in my Rails 3 project and it is really slow!
Here's the code sample:
# ...
User.create!(
:display_name => "#{title} #{name} #{surname}",
:email => "#{name}.#{surname}_#{num}#localtinkers.com",
:password => '12341234'
)
It works, but it is really slow because for each user:
Devise issues a SELECT statement to find out if the email is already taken.
A separate INSERT statement is issued.
For other objects I use "ar-extensions" and "activerecord-import" gems as follows:
tags.each do |tag|
all_tags << Tag.new(:name => tag)
end
Tag.import(all_tags, :validate => false, :ignore => true)
The above creates just one INSERT statement for all the tags and it works really fast, just like MySql database restore from the SQL dump.
But for users I cannot do this because I need Devise to generate encrypted password, salt, etc for each user. Is there a way to generate them on the SQL side or are there other efficient ways of seeding users?
Thank you.
How about:
u = User.new(
:display_name => "#{title} #{name} #{surname}",
:email => "#{name}.#{surname}_#{num}#localtinkers.com",
:password => '12341234'
)
u.save!(:validate => false)
This should create and save the record without executing the validations, and therefore without checking for e-mail address uniqueness. Obviously the downside of this is that you're not being protected by any other validations on the user too, so make sure you check your data first!
I am using this method for search engine friendly URLs in Rails - http://jroller.com/obie/entry/seo_optimization_of_urls_in
My model looks like this.
class Listing < ActiveRecord::Base
def to_param
"#{id}-#{title.parameterize}"
end
end
This works with MySQL but not Postgresql.
This is the error I get:
ActiveRecord::StatementInvalid (PGError: ERROR: invalid input syntax for integer: "16- college-station-apartments"
: SELECT * FROM "floorplans" WHERE ("floorplans"."listing_id" = E'16-college-station-apartments') ORDER BY beds ASC, baths ASC, footage ASC, price ASC):
Is ActiveRecord not doing a .to_i on the find for Postgresql?
Rails will automatically call to_i on your parameter for some methods, mainly those where an integer is expected as a parameter, like Listing.find(params[:id]).
However, for other types of search methods that can accept strings as parameters, you'll need to manually call to_i
Listing.find_by_id(params[:id].to_i)
Listing.find(:conditions => ["id = ?", params[:id].to_i])
The reason you're not having a problem with MySQL is that MySQL does what would in effect be a to_i on its end (i.e. it's not a database-adapter issue, but rather a capability of the actual database server).