过滤属性无法正常工作



我有一个具有多个has_many关联的用户类。我有一个净支付页面,将显示每个用户及其关联。我希望能够过滤以仅显示所选月/年的关联,而我目前似乎无法使用。

用户控制器

 def net_pay
    @users = User.all.order(driver_id: :asc)
    @users.each do |user|
      search_date(user)
    end
 end
def show
  if params[:month_select]
    search_date(@user)
    total_deductions
  else
    @trips
  end
end
def search_date(user)
  @trips = user.trips.month_year(params[:month_select],params[:year_select])
  @advances = user.advances.month_year(params[:month_select],params[:year_select])
  @prorates = user.prorates.month_year(params[:month_select],params[:year_select])
  @icbcs = user.icbcs.month_year(params[:month_select],params[:year_select])
  @dentals = user.dentals.month_year(params[:month_select],params[:year_select])
  @others = user.others.month_year(params[:month_select],params[:year_select])
  @admin_expenses = user.admin_expenses.month_year(params[:month_select],params[:year_select])
end

搜索对单个用户有效,但是当我需要迭代所有用户以获得每个用户的一个月/年时,它无法保存。任何帮助将不胜感激。

迭代每次循环用户循环时都会覆盖实例变量。

您可以尝试将monthyear作为实例变量传递到视图,然后通过@users在迭代中调用user.trips.month_year(@month, @year)。或者,您可以创建一个对象,该对象获取用户,月和年的参数,并返回您期望的值。@net_pay_users = @users.map { |user| UserNetPayBuilder.new(user, params[:month_select], params[:year_select]) },然后在您的视图中通过@net_pay_users迭代。

def initialize(user, month, year)
  self.user = user
  ...
end
def trips
  user.trips.month_year(month, year)
end

您可以进一步重构构建器接受一组用户并将有用对象的集合返回给您,而不是在控制器内使用map

最新更新