Sample Mongodb collection
[
{"sno":4,"data":"data-4"},
{"sno":3,"data":"data-3"},
{"sno":2,"data":"data-2"},
{"sno":1,"data":"data-1"},
]
Spring Data Code:
PageRequest pageable = new PageRequest(page--, size);
return dao.findAll(pageable);
If I pass page as 1 and size as 1, i m getting the below result, which is correct.
{"sno":4,"data":"data-4"}
If I pass page as 1 and size as 2, see the below
Expected:
{"sno":4,"data":"data-4"}
{"sno":3,"data":"data-3"}
Actual:
{"sno":3,"data":"data-3"}
{"sno":2,"data":"data-2"}
It skips the first record, looks like its a issue with Spring Data for mongodb implementation. I have tried with explicit Sort(DESC,"sno") in pageable, still same result.
Did anyone experience this issue?
Actually page starts from 0.
I've tried the same data as you and actually if I call:
PageRequest pageable = new PageRequest(0, 1, new Sort(Sort.Direction.DESC, "sno"));
dao.findAll(pageable);
I will get:
{"sno":4,"data":"data-4"}
The same if you need first two records in order just call with
new PageRequest(0, 2, new Sort(Sort.Direction.DESC, "sno"));
I am new to rails. What I see that there are a lot of ways to find a record:
find_by_<columnname>(<columnvalue>)
find(:first, :conditions => { <columnname> => <columnvalue> }
where(<columnname> => <columnvalue>).first
And it looks like all of them end up generating exactly the same SQL. Also, I believe the same is true for finding multiple records:
find_all_by_<columnname>(<columnvalue>)
find(:all, :conditions => { <columnname> => <columnvalue> }
where(<columnname> => <columnvalue>)
Is there a rule of thumb or recommendation on which one to use?
where returns ActiveRecord::Relation
Now take a look at find_by implementation:
def find_by
where(*args).take
end
As you can see find_by is the same as where but it returns only one record. This method should be used for getting 1 record and where should be used for getting all records with some conditions.
Edit:
This answer is very old and other, better answers have come up since this post was made. I'd advise looking at the one posted below by #Hossam Khamis for more details.
Use whichever one you feel suits your needs best.
The find method is usually used to retrieve a row by ID:
Model.find(1)
It's worth noting that find will throw an exception if the item is not found by the attribute that you supply. Use where (as described below, which will return an empty array if the attribute is not found) to avoid an exception being thrown.
Other uses of find are usually replaced with things like this:
Model.all
Model.first
find_by is used as a helper when you're searching for information within a column, and it maps to such with naming conventions. For instance, if you have a column named name in your database, you'd use the following syntax:
Model.find_by(name: "Bob")
.where is more of a catch all that lets you use a bit more complex logic for when the conventional helpers won't do, and it returns an array of items that match your conditions (or an empty array otherwise).
Model.find
1- Parameter: ID of the object to find.
2- If found: It returns the object (One object only).
3- If not found: raises an ActiveRecord::RecordNotFound exception.
Model.find_by
1- Parameter: key/value
Example:
User.find_by name: 'John', email: 'john#doe.com'
2- If found: It returns the object.
3- If not found: returns nil.
Note: If you want it to raise ActiveRecord::RecordNotFound use find_by!
Model.where
1- Parameter: same as find_by
2- If found: It returns ActiveRecord::Relation containing one or more records matching the parameters.
3- If not found: It return an Empty ActiveRecord::Relation.
There is a difference between find and find_by in that find will return an error if not found, whereas find_by will return null.
Sometimes it is easier to read if you have a method like find_by email: "haha", as opposed to .where(email: some_params).first.
Since Rails 4 you can do:
User.find_by(name: 'Bob')
which is the equivalent find_by_name in Rails 3.
Use #where when #find and #find_by are not enough.
The accepted answer generally covers it all, but I'd like to add something,
just incase you are planning to work with the model in a way like updating, and you are retrieving a single record(whose id you do not know), Then find_by is the way to go, because it retrieves the record and does not put it in an array
irb(main):037:0> #kit = Kit.find_by(number: "3456")
Kit Load (0.9ms) SELECT "kits".* FROM "kits" WHERE "kits"."number" =
'3456' LIMIT 1
=> #<Kit id: 1, number: "3456", created_at: "2015-05-12 06:10:56",
updated_at: "2015-05-12 06:10:56", job_id: nil>
irb(main):038:0> #kit.update(job_id: 2)
(0.2ms) BEGIN Kit Exists (0.4ms) SELECT 1 AS one FROM "kits" WHERE
("kits"."number" = '3456' AND "kits"."id" != 1) LIMIT 1 SQL (0.5ms)
UPDATE "kits" SET "job_id" = $1, "updated_at" = $2 WHERE "kits"."id" =
1 [["job_id", 2], ["updated_at", Tue, 12 May 2015 07:16:58 UTC +00:00]]
(0.6ms) COMMIT => true
but if you use where then you can not update it directly
irb(main):039:0> #kit = Kit.where(number: "3456")
Kit Load (1.2ms) SELECT "kits".* FROM "kits" WHERE "kits"."number" =
'3456' => #<ActiveRecord::Relation [#<Kit id: 1, number: "3456",
created_at: "2015-05-12 06:10:56", updated_at: "2015-05-12 07:16:58",
job_id: 2>]>
irb(main):040:0> #kit.update(job_id: 3)
ArgumentError: wrong number of arguments (1 for 2)
in such a case you would have to specify it like this
irb(main):043:0> #kit[0].update(job_id: 3)
(0.2ms) BEGIN Kit Exists (0.6ms) SELECT 1 AS one FROM "kits" WHERE
("kits"."number" = '3456' AND "kits"."id" != 1) LIMIT 1 SQL (0.6ms)
UPDATE "kits" SET "job_id" = $1, "updated_at" = $2 WHERE "kits"."id" = 1
[["job_id", 3], ["updated_at", Tue, 12 May 2015 07:28:04 UTC +00:00]]
(0.5ms) COMMIT => true
Apart from accepted answer, following is also valid
Model.find() can accept array of ids, and will return all records which matches.
Model.find_by_id(123) also accept array but will only process first id value present in array
Model.find([1,2,3])
Model.find_by_id([1,2,3])
The answers given so far are all OK.
However, one interesting difference is that Model.find searches by id; if found, it returns a Model object (just a single record) but throws an ActiveRecord::RecordNotFound otherwise.
Model.find_by is very similar to Model.find and lets you search any column or group of columns in your database but it returns nil if no record matches the search.
Model.where on the other hand returns a Model::ActiveRecord_Relation object which is just like an array containing all the records that match the search. If no record was found, it returns an empty Model::ActiveRecord_Relation object.
I hope these would help you in deciding which to use at any point in time.
Suppose I have a model User
User.find(id)
Returns a row where primary key = id. The return type will be User object.
User.find_by(email:"abc#xyz.com")
Returns first row with matching attribute or email in this case. Return type will be User object again.
Note :- User.find_by(email: "abc#xyz.com") is similar to User.find_by_email("abc#xyz.com")
User.where(project_id:1)
Returns all users in users table where attribute matches.
Here return type will be ActiveRecord::Relation object. ActiveRecord::Relation class includes Ruby's Enumerable module so you can use it's object like an array and traverse on it.
Both #2s in your lists are being deprecated. You can still use find(params[:id]) though.
Generally, where() works in most situations.
Here's a great post: https://web.archive.org/web/20150206131559/http://m.onkey.org/active-record-query-interface
The best part of working with any open source technology is that you can inspect length and breadth of it.
Checkout this link
find_by ~> Finds the first record matching the specified conditions. There is no implied ordering so if order matters, you should specify it yourself. If no record is found, returns nil.
find ~> Finds the first record matching the specified conditions , but if no record is found, it raises an exception but that is done deliberately.
Do checkout the above link, it has all the explanation and use cases for the following two functions.
I will personally recommend using
where(< columnname> => < columnvalue>)
I have small problem. Lets say I have users 1, 2 and 4. And now I'm trying to use this query:
User.select(:channel).where(:id => rand(1..User.count)).first.channel
Which in this case works like this:
User.select(:channel).where(:id => rand(1..3)).first.channel
And well, thats my problem. I can select user 1 and user 2. User 4 is unreachable. And if it try to take user 3 it returns me that there is no .channel method, because everything is nil then... What should I do so it could reach users 1, 2, 4 and ignore user 3 which is nil?
You could first get the list of available record IDs and then pick a random id:
ids = User.pluck(:id)
User.select(:channel).where(:id => ids.sample).first.channel
But of course that requires two queries so if that isn't efficient enough you could try telling the DB itself to select a random record. For example, if you're using MySQL you could so something like this:
User.order('rand()').limit(1)
I'm learning about models and databases in rails and when I create a table I can call .allon the model and get a empty array, but if I create multiple rows and I call .all I get an array where only the first row shows actual values and the rest are #.
Why doesnt the console display all the row values and if it doesn't how can I see all the values of the rows without calling .find on each one?
irb(main):001:0> Todo.all
Todo Load (0.1ms) SELECT "todos".* FROM "todos"
[#<Todo id: 1, todo_item: "pick up milk", created_at: "2014-07-27 15:45:11", updated_at:
"2014-07-27 15:45:11">, #, #]
irb(main):001:0> Todo.all.second
Todo Load (0.1ms) SELECT "todos".* FROM "todos"
#<Todo id: 2, todo_item: "Pay internet bill", created_at: "2014-07-27 15:47:42", updated_at: "2014-07-27 15:47:42">
I'm pretty sure this is a feature of the console, shortening the output to show you the attributes of the model without filling the output space. If you need to see the actual attributes try collect for the contents you want to see:
TODO.all.collect{|x| x.todo_item}
or for the whole object...
TODO.all.collect{|x| x.inspect}
A good approach is to write a custom to_s method with the content you most commonly want to see and use that. In your model...
def to_s
"TODO: #{id} - #{todo_item}"
end
and use it like this:
TODO.all.collect{|x| x.to_s}
the upshot of the custom to_s is that it will also be used by a lot of debugging tools and by ruby string injections.
In my controller i am getting all entries form a table like this
#enums = Enuemerations.all
Then later i want to search and get the name from by doing
#enums.find(107).name
I get an error
undefined method `name' for #<Enumerator:0xb5eb9d98>
So I tried it out in the rails console and found this working
Enumeration.where(false).find(107)
where this does not work
Enumeration.all.find(107)
Can someone explain to me how this works?
Thanks
Using Enumeration.all instantly queries the database returning an Array with all the Enumeration records (if you only want a single record this would be very inefficient). It no longer knows about the ActiveRecord methods:
> Enumeration.all.class
Enumeration Load (0.1ms) SELECT "enumerations".* FROM "enumerations"
=> Array
Calling find on an Array uses Enumerable#find which would need a different syntax, e.g:
enums = Enumeration.all
enum = enums.find { |e| e.id == 2 }
=> #<Enumeration id: 2, name: "...">
Using Enumeration.where(false) only returns a lazy ActiveRecord::Relation, it doesn't actually hit the database (yet), this allows you to chain extra ActiveRecord methods such as find in your example above.
> Enumeration.where(false).class
=> ActiveRecord::Relation
> Enumeration.where(false).find(2)
Enumeration Load (0.2ms) SELECT "enumerations".* FROM "enumerations" WHERE "enumerations"."id" = ? LIMIT 1 [["id", 2]]
=> #<Enumeration id: 2, name: "...">