bogdan / datagrid

Gem to create tables grids with sortable columns and filters
MIT License
1.02k stars 115 forks source link

Passing current_user to filter with a checkbox #291

Closed Ellerden closed 4 years ago

Ellerden commented 4 years ago

Hello again :) I'm trying to access from the filter current_user that passed to my CandidatesGrid. I've read docs, this Issue and several others about select. It all works if select is not a checkbox, I guess – or I couldn't find a way around it. My filter looks like this and I get "undefined local variable or method `current_user'" , but if I replace it with some user.id it works. What could be wrong? Thanks for your help!

attr_accessor :current_user

filter(
    :followers,
    :enum,
    :select => ['Followed'],
    checkboxes: true
    ) do |stage|
        joins(:followers).where('users.id = ?', current_user.id)
    end
bogdan commented 4 years ago

The best way to use current_user fo scope control is like this:

def index
  @grid = CandidatesGrid.new(params[:candidates_grid]) do |s|
    s.where("users.id = ?", current_user.id).page(params[:page])
  end
end

If you still want current_user to be inside Grid for any purpose, define it as filter:

filter(:current_user) do
  where('users.id = ?', current_user.id)
end
Ellerden commented 4 years ago

Yeah, I will need current_useronly for one filter, not for the whole scope of candidates.

Ellerden commented 4 years ago

I found a way around it — since I at least needed current_user id to make my filter work and to avoid stack level is too deep error.

in controller: current_user_id = current_user.id and then passing to the gridcurrent_user_id instead of current_user

in CandidatesGrid:

  attr_accessor :current_user_id

  filter(
    :followed,
    :enum,
    select: ['Followed'],
    checkboxes: true
  ) do |_value, scope, grid|
      scope.joins(:followers).where('users.id = ?', grid.current_user_id)
  end