Solve active record query issues