lundi 23 février 2015

Why does my method not work?

In my cinema ruby on rails application I am trying to display the amount of seats that have been booked for a showing in a screen. I have taken code from this question: Count the amount of records are associated to another record


And so have added this code to my screens.rb model:



def remaining_seats
seats.count - ( bookings || [] ).count
end

def screens_info
"#{name} (#{remaining_seats}/#{seats.count} remaining)"
end


And display this on the view:



<%= @booking.showing.screen.screens_info %>


But the code in remaining_seats: ( bookings || [] ).count returns 0, so the whole thing will tell me all seats are available.


This is my screen.rb model:



class Screen < ActiveRecord::Base
has_many :seats
has_many :showings
has_many :bookings, through: :showings
def screens_info
"#{name}"
end

def self.showing_search(showing_id)
if not showing_id.blank?
screen = Showing.find(showing_id).screen_id
self.where("id = ?", screen)
end
end

def remaining_seats
seats.count - ( bookings || [] ).count
end

def screens_info
"#{name} (#{remaining_seats}/#{seats.count} remaining)"
end
end


showing.rb:



class Showing < ActiveRecord::Base
belongs_to :film
has_many :bookings
belongs_to :screen
end


booking.rb:



class Booking < ActiveRecord::Base
belongs_to :user
belongs_to :showing
end


And the schema:



create_table "seats", force: :cascade do |t|
t.string "seat"
t.integer "screen_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end

create_table "showings", force: :cascade do |t|
t.date "show_date"
t.time "show_time"
t.integer "film_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "screen_id"
end

create_table "screens", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end

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 "seats_quantity"
end


So just to clarify, what I am trying to do is display the amount of seats that are available to be booked for a particular showing in a specific screen - so say a screen has 25 seats and at the 13:00 showing 5 seats have been booked I want to say there are 20 seats remaining.


Aucun commentaire:

Enregistrer un commentaire