AnthonyGalli.com AnthonyGalli.com - 1 month ago 12
Ruby Question

compared with non class/module in controller

How to only include users who have more than 0

challenges.publish
?

class UsersController < ApplicationController
def index
@users, @alphaParams = User.select{ |user| user.challenges.publish > 0}.alpha_paginate(params[:letter], {:pagination_class => "pagination-centered"}){|user| user.name}
end
end


Maybe I should use
where
instead of
select
?

Answer

You can combine joins, where and distinct to avoid select same records.

User.joins(:challenges).where('challenges.publish > 0').distinct

Using ruby methods like map, select etc. with active records method is bad behavior, because it can provide to n+1 problems or other errors.