我试图获得每位用户加班费的sum
不每次预订,这就是现在正在做的事情:Imgur
控制器
def index
@users = User.all
@hospital_bookings = HospitalBooking.scoped
end
end
Index.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
Schema.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) %>
答案 0 :(得分: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 %>