1

我正在尝试获得sum每个用户的加班时间而不是每次预订,这就是它现在正在做的事情:Imgur

控制器

def index
    @users = User.all
    @hospital_bookings = HospitalBooking.scoped
  end
end

索引.html.erb

<%@users.each do |user|%>
  <% user.hospital_bookings.each do |hospital_booking| %>
   {
      name:'<%= hospital_booking.user.try(:name)%>',
      data:[<%= @hospital_bookings.where(:user_id => 
     hospital_booking.user.id).all.sum(&:overtime)%>]
    },
  <% end %>
 <% end %>

楷模

#User.rb
has_many :hospital_bookings

#hospital_booking
belongs_to :user

架构.rb

create_table "hospital_bookings", :force => true do |t|
    t.string   "booking_reference"
    t.datetime "created_at",                                       :null => false
    t.datetime "updated_at",                                       :null => false
    t.integer  "hospital_id"
    t.integer  "user_id"
    t.date     "day"
    t.string   "shift_type"
    t.decimal  "overtime",          :precision => 10, :scale => 0
  end

我尝试了以下方法,但这些似乎都不起作用。

**Attempt1**
<%= @hospital_bookings.where(:user_id => user.id, :hospital_booking =>
 hospital_id ).all.sum(&:overtime)%>

**Attempt2**
<%= HospitalBooking.where(user_id: user.id, 
 hospital_id: hospital.id).sum(:overtime) %> 
4

1 回答 1

1

您似乎要求给定用户的所有加班时间的总和user

user.hospital_bookings.sum(:overtime)

并且仅限于给定的医院

user.hospital_bookings.where(:hospital_id => hospital.id).sum(:overtime)

(但这应该与您的Attempt2相同)

评论后编辑
您的第二次迭代创建了重复项。如果您仅对用户进行迭代并将他们的加班时间相加,您应该得到您想要的输出。

<% @users.each do |user|%>
   {
      name:'<%= user.name %>',
      data:[<%= user.hospital_bookings.sum(&:overtime)%>]
    },
 <% end %>
于 2013-03-02T14:11:16.173 回答