[英]How to make a variable set in controller, available in other class?
In my controller I have: 在我的控制器中,我有:
def index
@grid = UsersGrid.new(params[:users_grid]) do |scope|
scope.where(admin: false).page(params[:page]).per_page(30)
end
@grid.assets
if (current_user && current_users.admin?)
@show_column = true
else
@show_column = false
end
end
In my grid class: 在我的网格课程中:
class UsersGrid
include Datagrid
scope do
User.order("users.created_at desc")
end
column(:abc, :header => "abc?", :html => true, :if => proc {@show_column == true}) do |user|
image_tag("abc.png", title: "abc") if user.abc
end
end
So in the controller I set @show_column
, and in the class it should show the column :abc
depending on whether @show_column
is true or false. 因此,在控制器中,我设置了@show_column
,并在类中根据@show_column
是true还是false来显示:abc
列。 This goes wrong as @show_column
is an instance variable and not available in the grid class. 这是错误的,因为@show_column
是实例变量,在网格类中不可用。 So it's nil. 所以它是零。 How should I change this to make this work? 我应该如何更改才能使它正常工作?
You can pass down the variable when creating the UsersGrid
instance, then save it in an instance variable there. 您可以在创建UsersGrid
实例时传递该变量,然后将其保存在该实例变量中。
In controller: 在控制器中:
def index
@show_column = (current_user && current_users.admin?)
@grid = UsersGrid.new(params[:users_grid], @show_column) do |scope|
scope.where(admin: false).page(params[:page]).per_page(30)
end
@grid.assets
end
In the grid class: 在网格类中:
class UsersGrid
def initialize(*params, show_column)
super *params
@show_column = show_column
end
# ...
end
You can use attr_accessor for a variable that is not a column of a table. 您可以将attr_accessor用于不是表的列的变量。
def index
params[:users_grid][:show_column] = (current_user && current_users.admin?)
@grid = UsersGrid.new(params[:users_grid]) do |scope|
scope.where(admin: false).page(params[:page]).per_page(30)
end
@grid.assets
end
class UsersGrid
include Datagrid
scope do
User.order("users.created_at desc")
end
attr_accessor :show_column
column(:abc, :header => "abc?", :html => true, :if => proc {self.show_column == true}) do |user|
image_tag("abc.png", title: "abc") if user.abc
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.