0

在我的 Rails 应用程序中,我有两个实例变量 @departments 和 @register

@部门=

{
    "users": [
        {
            "departmentid": "DP11"
        },
        {
            "departmentid": "DP12"
        },
        {
            "departmentid": "DP13"
        },
        {
            "departmentid": "DP10"
        }
    ]
}

@注册=

{
    "attendance": [
        0,
        0,
        2,
        1
    ]
}

@register 包含一个数组。

是否可以使用 rabl (attendancebydepartment.json.rabl) 视图显示如下格式

{
        "users": [
            {
                "departmentid": "DP11",
                "attendance"=0
            },
            {
                "departmentid": "DP12",
                "attendance"=0
            },
            {
                "departmentid": "DP13",
                "attendance"=2
            },
            {
                "departmentid": "DP10",
                "attendance"=1
            }
        ]
    }

我的控制器看起来像

def attendancebydepartment
    @register = Array.new
    @departments = User.select('departmentid').uniq
    startdate = params[:startdate]
    enddate = params[:enddate]
    @count = @departments.count
    @departments.each do |d|
    @register << (Register.where(:date => startdate..enddate , :departmentid => d.departmentid).sum(:one))+(Register.where(:date => startdate..enddate , :departmentid => d.departmentid).sum(:two))
    end
  end

是否可以将每个部门及其相应的出勤率添加到数组中,以便我可以显示预期的格式。

4

2 回答 2

0

OpenStruct使用类似这样的方法在控制器中创建对象可能是最简单的,但我建议重新编写attendancebydepartment以不循环两次。

@users = []
@departments.each_with_index do |dep, index|      
  user = OpenStruct.new
  user.departmentid = dep.departmentid
  user.attendence = @register[index].attendence
  @users << user
end

在视图中:

collection @users => :users
attribute :departmentid, :attendence
于 2013-01-04T05:40:43.403 回答
0

也许使用该zip方法创建一个新变量然后呈现它。

irb(main):001:0> departments = {'users' => [{'id' => 1}, {'id' => 2}]}
=> {"users"=>[{"id"=>1}, {"id"=>2}]}

irb(main):002:0> register = {'attendance' => [0,1]}
=> {"attendance"=>[0, 1]}

irb(main):004:0> departments['users'].zip(register['attendance'])
=> [[{"id"=>1}, 0], [{"id"=>2}, 1]]

另一方面,看起来更简单的设计是拥有一个与 关联的Department模型。然后,您可以直接从.has_manyUsersDepartment

于 2013-01-04T05:28:17.203 回答