sqlite - Rails app with postgresql; query with .take does not keep the order of records -


i have rails 4 application , switched sqlite postgresql. have following 3 models;

class user < activerecord::base     has_many :user_games     has_many :games, :through => :user_games end  class game < activerecord::base     has_many :user_games     has_many :users, :through => :user_games end  class usergame < activerecord::base     belongs_to :user     belongs_to :game end 

with records:

game id 1   usergame id  user_id   game_id 1      5         1 2      3         1  user id 1 2 

i sqlite:

game = game.find(1) game.users.take(2).first 

which return user id 5.

the same code postgres gives user id 3.

why?

edit:

i forgot add need users in order appear in table.

so if...

game id 1  2  usergame id  user_id   game_id 1      5         1 2      3         1 3      1         2 4      4         2  user id 1 2 3 4 

... need query preserves order of users, game1.users.first.id = 5 , game2.users.first.id = 1

game1.users.take(2).first.id preserve order when used sqlite, postgresql not.

take has following explanation in manual:

take

gives record (or n records if parameter supplied) without implied order. order depend on database implementation. if order supplied respected. 

if want same result postgresql , sqlite specify default order.

game.users.order('users.id desc').first 

or since last , first method` sorts data in rails 4 use:

game.users.last 

this translate following sql:

select * users "games"."id" = 1 order "users"."id" desc limit 1 

my conclusion don't need use take @ all

edit

you have:

game = game.find(1) users = game.users.order("user_games.id asc").take(2) 

then, if iterate on users collection:

users.each |user|   puts user.inspect end 

you should users ordered want.


Comments

Popular posts from this blog

java - Could not locate OpenAL library -

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

sorting - opencl Bitonic sort with 64 bits keys -