Ruby on Rails Why do I get the error: Array can't be coerced into Fixnum

Ruby on Rails Why do I get the error: Array can't be coerced into Fixnum

我正在 Rails 的 Ruby 中制作一个影院系统,我目前正在尝试让它显示每次预订的总价。

我正在尝试通过 booking.rb 中的这种方法来做到这一点:

def total_price
    adult_price = Price.where("name = ?", "Adult").pluck(:price)
    child_price = Price.where("name = ?", "Child").pluck(:price)
    senior_price = Price.where("name = ?", "Senior").pluck(:price)
    student_price = Price.where("name = ?", "Student").pluck(:price)
    user = user_id
    showing = showing_id
    price = 0
    seats = Booking.where("user_id = ? and showing_id = ?", user,showing)
    seats.each do |seat|
        if not seat.adult_seats.blank?
            price = seat.adult_seats * adult_price
        end
        if not seat.child_seats.blank?
            price = price + (seat.child_seats * child_price)
        end
        if not seat.senior_seats.blank?
            price = price + (seat.senior_seats * senior_price)
        end
        if not seat.student_seats.blank?
            price = price + (
            seat.student_seats * student_price)
        end
    end
    price
end

但是我得到这个错误:

TypeError in Bookings#index 
Showing C:/Sites/Thor/Under Construction/ThorCinema/new/Lab/Newu/ThorCinema/app/views/bookings/index.html.erb where line #113 raised: 
Array can't be coerced into Fixnum

它在 bookings/index.html.erb 中引用的行是:

<% if not booking.total_price.blank? %><%= booking.total_price %><% end %>

有人能帮忙吗?

我可以确定错误与所选择的价格有关,因为如果我将方法更改为:

def total_price
    adult_price = Price.where("name = ?", "Adult").pluck(:price)
end

这显示在视图上:

    [#<BigDecimal:b20cbd8,'0.95E1',18(36)>]

这是预订和价格的架构table:

create_table "bookings", force: :cascade do |t|
  t.integer  "user_id"
  t.integer  "showing_id"
  t.datetime "created_at",     null: false
  t.datetime "updated_at",     null: false
  t.integer  "adult_seats"
  t.integer  "child_seats"
  t.integer  "senior_seats"
  t.integer  "student_seats"
  t.integer  "disabled_seats"
  t.integer  "immortal_seats"
end

create_table "prices", force: :cascade do |t|
  t.text     "name"
  t.decimal  "price"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

根据API Docpluckreturns一个数组。

尝试提取 pluck 的最后一个元素并将其显示在视图中。

所以,从本质上讲,您可能会看到的是 Price.where("name = ?", "Adult").pluck(:price).lastPrice.where("name = ?", "Adult").pluck(:price).first