Search code examples
ruby-on-railsarraysruby-on-rails-3decimalbigdecimal

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


I am making a cinema system in Ruby on Rails, I am currently trying to get it to display the total price of each booking.

I am trying to do this through this method in 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

But I get this error:

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

The line it is referring to in bookings/index.html.erb is:

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

Can anyone help?

I can determine that the error is something to do with the prices that are being picked because if I change the method to:

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

This displays on the view:

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

This is the schema of the bookings and prices 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

Solution

  • According to the API Doc pluck returns an array.

    Try to extract the last element of the pluck and display it in the view.

    So, essentially, what you might be looking at would be Price.where("name = ?", "Adult").pluck(:price).last or Price.where("name = ?", "Adult").pluck(:price).first