1

I have a model that is paginated, and in some cases I want to add an extra column to the query and retrieve that same column in my paginated results. For example:

users = User.select('users.*, users.value is NULL as val').page(2)

If I do users.first['val'] then it gives me nothing. But if I remove the pagination users = User.select('users.*, users.value is NULL as val') then users.first['val'] will give me what I want. How can I do this with Kaminari?

Guillaume
  • 2,912
  • 3
  • 35
  • 59
  • Please post your full query (and ideally the relevant parts of models with association definitions) as **your sample query seems to work OK** with Kaminari and thus there's currently no problem to solve. – Matouš Borák Mar 23 '16 at 05:30

1 Answers1

0

I see a few problems with your code and my tests show that what you want should work OK with Kaminari.

First, you write that you want to "add extra" columns to the query, then you should select also the User object itself, not only the extra column:

users = User.select('users.*, users.value is NULL as val')

Next, you probably forgot to select a user from the returned (paginated) array before accessing the attribute, so instead of:

users['val']

you probably should do something like:

users.first['val']

And finally, see my test for Kaminari and a custom column in select (my column tested for null is name instead of value but the principle is the same):

>> User.page(1).map(&:name)
=> ["ddddd", nil, nil, nil, "0", nil]

>> User.select('users.name is NULL as val').page(1).map{ |user| user['val'] }
=> [0, 1, 1, 1, 0, 1]

So, it seems to work!

Matouš Borák
  • 15,606
  • 1
  • 42
  • 53
  • ah yes sorry for the bad coding, I went a bit too fast to write the code, I updated the question. Actually the query is a lot more complicated than that, with a few `joins` and `includes`, could it be the problem? btw, your second query should be `User.select('users.*, users.name is NULL as val').page(1).map{ |user| user['val'] }` to match the first problem – Guillaume Mar 23 '16 at 04:36
  • so I think I found out what the problems comes from, and it is because I also do an `includes` in the query, and there seems to be a well-known problem between `select` and `includes` with `ActiveRecord`: http://stackoverflow.com/a/4048882/517193 – Guillaume Mar 29 '16 at 01:45
  • OK and do you still need to help with this somehow? If yes, please add the complete query to your question. – Matouš Borák Mar 29 '16 at 05:23