I am sending an array from jquery via the url requerts to the rails controller.
when I do this in my controller
log_array = (params[:log_ids])
logger.debug "This is the array #{log_array.to_a}"
I get this in my server log
This is the array 85,84,83,82
I am trying this query to get all the selected logs:
#logs = Log.where(['"logs"."id" IN (?)', log_array])
I get this on the server log
SELECT "logs".* FROM "logs" WHERE ("logs"."id" IN ('85,84,83,82'))
It sould be like this
SELECT "logs".* FROM "logs" WHERE ("logs"."id" IN (85,84,83,82))
It seems like it puts the arry in like a string.
Is there any way to make the sql right for an array?
You're making things too SQL-ish. Try this:
Log.find_all(params[:log_ids])
Or Log.where(:id => params[:log_ids]) if you want to use where() goodness.
Would use the .where listed below...check out the link to the rails 3.1 deprecations.
http://m.onkey.org/active-record-query-interface
Related
I want to use raw sql in ruby on rails to retrieve data,for faster response.
I use
#test1=ActiveRecord::Base.connection.execute("select Unique Id from device_tables")
Then I test it use a p tag to display it in view:
<p><%= #test1 %></p>
But instead of give me data,it displays a relation:
#<Mysql2::Result:0x00000008664948>
I want to get the content of database,store all unique ids in a array.
You should iterate it using each or map to get results on view. Your current object look like this :
#<Mysql2::Result:0xcd3dfe0 #query_options={:as=>:array, :async=>false, :cast_booleans=>false, :symbolize_keys=>false, :database_timezone=>:utc, :application_timezone=>nil, :cache_rows=>true, :connect_flags=>-2147442171, :cast=>true, :default_file=>nil, :default_group=>nil, :adapter=>"mysql2", :database=>"GetTravelTime_Development", :host=>"localhost", :pool=>5, :username=>"root", :password=>nil, :timeout=>5000, :flags=>2}>
I have tried it on console for single and multiple object like this :
mysql_object = ActiveRecord::Base.connection.execute("select Unique Id from device_tables")
mysql_object.each{|object| puts object}
mysql_object.map{|object| puts object}
You can try find_by_sql method.eg:
TableName.find_by_sql"select * from table_names"
I'm missing something simple - I do not want to access the results of this query in a view.
Here is the query:
#adm = Admin.where({:id => {"$ne" => params[:id].to_s},:email => params[:email]})
And of course when you inspect you get:
#adm is #<MongoMapper::Plugins::Querying::DecoratedPluckyQuery:0x007fb4be99acd0>
I understand (from asking the MM guys) why this is the case - they wished to delay the results of the actual query as long as possible, and only get a representation of the query object until we render (in a view!).
But what I'm trying to ascertain in my code is IF one of my params matches or doesn't match the result of my query in the controller so I can either return an error message or proceed.
Normally in a view I'm going to do:
#adm.id
To get the BSON out of this. When you try this on the Decorated Query of course it fails:
NoMethodError (undefined method `id' for #<MongoMapper::Plugins::Querying::DecoratedPluckyQuery:0x007fb4b9e9f118>)
This is because it's not actually a Ruby Object yet, it's still the query proxy.
Now I'm fundamentally missing something because I never read a "getting started with Ruby" guide - I just smashed my way in here and learned through brute-force. So, what method do I call to get the results of the Plucky Query?
The field #adm is set to a query as you've seen. So, to access the results, you'll need to trigger execution of the query. There are a variety of activation methods you can call, including all, first, and last. There's a little documentation here.
In this case, you could do something like:
adm_query = Admin.where({:id => {"$ne" => params[:id].to_s},:email => params[:email]})
#adm_user = adm_query.first
That would return you the first user and after checking for nil
if #adm_user.nil?
# do something if no results were found
end
You could also limit the query results:
adm_query = Admin.where( ... your query ...).limit(1)
I would like to be able to pull all records from the db:
u = User.all
And then once loaded be able to apply AR methods to the resulting collection:
u.first
Is this possible in rails?
Once you actually query the database, the results become an array instead of an ActiveRecord::Relation. (Though #first would still work fine, since it's a method that also exists on Array).
If you just need a starting point to build an ActiveRecord::Relation though, you can use scoped:
# Doesn't execute a query yet
u = User.scoped
# This now executes a query similar to SELECT * FROM users LIMIT 1
u.first
Note that in Rails 4.0, #all now does the same thing as #scoped (whereas in Rails 3, it returns an array).
Why don't you try it?
User.all doesn't return an AR collection it returns an Array. Get rid of the .all and you will have a working example.
In rails 3, I would like to do the following:
SomeModel.where(:some_connection_id => anArrayOfIds).select("some_other_connection_id")
This works, but i get the following from the DB:
[{"some_other_connection_id":254},{"some_other_connection_id":315}]
Now, those id-s are the ones I need, but I am uncapable of making a query that only gives me the ids. I do not want to have to itterate over the resulst, only to get those numbers out. Are there any way for me to do this with something like :
SomeModel.where(:some_connection_id => anArrayOfIds).select("some_other_connection_id").values()
Or something of that nautre?
I have been trying with the ".select_values()" found at Git-hub, but it only returns "some_other_connection_id".
I am not an expert in rails, so this info might be helpful also:
The "SomeModel" is a connecting table, for a many-to-many relation in one of my other models. So, accually what I am trying to do is to, from the array of IDs, get all the entries from the other side of the connection. Basicly I have the source ids, and i want to get the data from the models with all the target ids. If there is a magic way of getting these without me having to do all the sql myself (with some help from active record) it would be really nice!
Thanks :)
Try pluck method
SomeModel.where(:some => condition).pluck("some_field")
it works like
SomeModel.where(:some => condition).select("some_field").map(&:some_field)
SomeModel.where(:some_connection_id => anArrayOfIds).select("some_other_connection_id").map &:some_other_connection_id
This is essentially a shorthand for:
results = SomeModel.where(:some_connection_id => anArrayOfIds).select("some_other_connection_id")
results.map {|row| row.some_other_connection_id}
Look at Array#map for details on map method.
Beware that there is no lazy loading here, as it iterates over the results, but it shouldn't be a problem, unless you want to add more constructs to you query or retrieve some associated objects(which should not be the case as you haven't got the ids for loading the associated objects).
Hi
I wonder how to work around the problem I have with the pagination gem "Kaminari".
For what I've understood you cant paginate #user = User.all.page(5)?
But what if I have this code and want to paginate that, is it possible or do I need to change the code?
#price = Price.joins(:retailer, :retailer => :profile).
where(['product_id=? AND size_id=?', params[:prod_id], params[:si_id]]).
group(:retailer_id).order("SUM((prices.price * #{params[:amount].to_i}) + profiles.shippingCost)").all
The only thing I receive right now when applying.page(5) to that code is
undefined method `page' for #<Class:0x000001023c4558>
You don't need the .all because the joins call, along with where and group, is returning an array of objects for you that meet your criteria. Remove your .all and call page on the instance variable (which you might want to rename to #pages or something else plural).