I'm using ruby 1.9.2 and rails 3 with a postgresql 8.4 database.
I have the following piece of rails code.
#playersonline = Member.find(:all, :conditions => ["loggedIn = ?", true] )
And I get the following error when the line is encountered:
PGError: ERROR: column "loggedin" does not exist
Looking at the query it generates it shows the following:
SELECT "members".* FROM "members" WHERE (loggedIn = 't')
The loggedIn column does exist in my table, and it has a boolean data type.
Another thing that is odd, when I try to query just the loggedIn column via a sql browser I get the same error? i.e. select loggedIn from members
Thanks
Postgres is case-sensitive by default so loggedIn isn't the same as loggedin. Although you can override it, Rails convention is that variable name-parts are separates by an underscore.
I wouldn't recommend re-inventing the wheel. Go in and change the columnn name (and any other columns that follow your notation) you might have to logged_in. This will prevent you from encountering any more strange errors.
Related
I'm trying to understand how to use the select method in queries to return custom columns.
I'm running Rails 5.2, database is postgresql.
m = Message.all.select("messages.*, CASE WHEN id > 30 THEN TRUE ELSE FALSE END AS above_30")
returns only the messages table with all its columns. How do I get the above_30 column, preferable eager loaded?
The above_30 is there, but Rails will not define an access for it because there is no column by that name in your schema.
You can define one yourself, or use m[:above_30] to access the "raw" attributes of the object as returned from the query.
I am trying to use distinct on in rails with a scope, I've created a method in my model like this:
def self.fetch_most_recent_by_user(scope)
scope.where(guid: scope.except(:select).select("DISTINCT ON (eld_logs.user_id) user_id, eld_logs.guid").order("user_id, eld_logs.created_at desc").map(&:guid))
end
When I execute this I get and error like:
TestModel.fetch_most_recent_by_user(TestModel.includes(:user))
ERROR: syntax error at or near "DISTINCT"
LINE 1: SELECT guid, DISTINCT ON (user_id) user_id...
On searching on DISTINCT ON I found out that it should be the first element in a select statement for postgres to make it work.
I want to prepend the DISTINCT ON in the select statement. I have tried clearing the old select statements using except(:select) which I got from here, but it doesn't work because the includes(:user) prepends users attributes first while doing a left join.
I am using Rails 4.0.13 and Postgres 9.4.12. Any help is appreciated.
I found that if the includes was meddling with the distinct my sub query, because which DISTINCT ON failed. I modified my method to this and it works:
def self.fetch_most_recent_eld_log_by_user(scope, include_associations = { })
scope.where(guid: scope.except(:select).select("DISTINCT ON (eld_logs.user_id) eld_logs.user_id, eld_logs.guid").order("eld_logs.user_id, eld_logs.created_at desc").map(&:guid))
.includes(include_associations)
end
Still it'll be good if someone can provide a way to prepend something in the select statement of active record scope.
Running Rails 4.0.13 with TinyTDS connected to Microsoft SQL Server 2012, I'm trying to run the following query:
sql = Model.where(:foo => bar).select(:open, :high, :low, :close).to_sql
Model.connection.execute(sql)
The problem is, the generated sql is
"SELECT open, high, low, close FROM [models]"
Which gives me an error as the column names open and close are protected.
TinyTds::Error: Incorrect syntax near the keyword 'open'
If I use #pluck, I can see the correct SQL is generated (with column names escaped):
"SELECT [models].[open], [models].[high], [models].[low], [models].[close] FROM [models]"
However, this produces an array, which is not what I want.
My question is how can i get #select to correctly quote the column names?
Thank you
I don't think you can make the select method to protect your column names when using symbols (maybe because different DBMS use different quoting identifiers), but you could pass your selection as a string :
sql = Model.where(:foo => bar).select("[open], [high], [low], [close]").to_sql
Model.connection.execute(sql)
I attempted to submit a bug report to Rails, however in doing so I saw the problem did not appear to exists using SQLite test case, this leads me to believe the issue is with the SQL Server Adapter.
Since I am on Rails 4 and not the latest version of the adapter I left it and wrote the following (horrible) method as wrapping the column names was not enough, I needed to prefix the table to prevent ambiguous column names. Yuck
def self.quote(*columns, klass)
columns.map { |col| "[#{klass.table_name}].[#{col}]" }.join(', ')
end
I moved my app from sqlite to postgresql so that I could use RGeo and PostGIS. I deleted all the data in my database and started from scratch. Everything is working fine except one particular area of the site. I have an association that links Tourstops and Venues that appears to be not working. No code was modified in this area since the switch. Unfortunately I'm still sort of new to rails and don't know enough to diagnose this error.
The error I'm getting is:
ActiveRecord::StatementInvalid in ToursController#show
PG::DatatypeMismatch: ERROR: argument of WHERE must be type boolean, not type integer LINE 1: SELECT "venues".* FROM "venues" WHERE (1) LIMIT 1 ^ : SELECT "venues".* FROM "venues" WHERE (1) LIMIT 1
def show
#tour = Tour.find(params[:id])
#tourstop = Venue.find_by(params[:id])
end
Parameters: {"id"=>"1"}
Your problem, as stated in the comments, that you're using find_by without any :key in the hash
To be clear, ActiveRecord should be able to translate between SQLite & PGSQL, so the difference has to be with your use of the ActiveRecord methods:
find
Finds individual element by primary_key:
Model.find(id)
find_by
Finds by value other than primary_key:
Model.find_by name: "Rich"
Model.find_by({name: "Rich"})
I'm trying to figure out where a whole pile of extra queries are being generated by my rails app. I need some ideas on how to tackle it. Or, if someone can give me some hints, I'd be grateful.
I get these:
SQL (1.0ms) SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
SQL (0.8ms) SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
SQL (0.8ms) SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
repeated over and over on every request to the DB (as much as 70 times for a single request)
I tried installing a plugin that traced the source of the queries, but it really didn't help at all. I'm using the hobofields gem, dunno if that is what's doing it but I'm somewhat wedded to it at the moment
Any tips on hunting down the source of these extra queries?
Have a look at ActiveRecord gem in connection_adapters/sqlite_adapter.rb on line 173 (I'm using ActiveRecord 3.0.7) you have a function called tables that generates the exact query you posted:
SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
In development mode this function gets called for every table from your database, on every request.
In production this function gets called only once, when the server starts, and the result is cached.
In development for each request rails looks into your database to see what columns each table has so it can generate methods on your models like "find_by_name". Since in production is unlikely that your database changes, rails does this lookup only on server start.
It's very difficult to tell this without look into the Code.
but i am sure you write your query in a certain loop
for i in 0..70
SqliteMaster.find(:all, :conditions=>["type=? and not name=?", 'table', 'sqlite_sequesnce'])
end
So my advice is that to check all the methods which gets called after requesting certain method and look whether the query called in a loop.
I've just seen this appearing in my logs when I do a search with the metasearch gem but ONLY in development mode.
I believe that it is caused by the plugin acts-as-taggable-on.
It will check if the table or the cache column exists.