简体   繁体   中英

Rails - counter_cache not working

I'm building an events app using Rails and have added a counter_cache association between my Event and Booking models in order to capture the number of bookings made on each event.

I'v added a line of code to my Event show page specifically for the creator of the event to show them how many bookings have been made -

 <% if user_signed_in? and current_user == @event.user %>
                        <button><%= link_to "Edit", edit_event_path %></button>
                        <button> <%= link_to "Delete", event_path, method: :delete, data: { confirm: "Are you sure?"} %></button>
                        <p><%= pluralize @event.bookings_count.size, 'booking' %></p>

All of the current events I have set up show exactly the same number of bookings (8 bookings) - 预订示例

When I try and add a booking it doesn't update. What am I doing wrong?

This is my migration from when I added bookings_count to my Events table -

class AddBookingsCountToEvents < ActiveRecord::Migration
  def change
     add_column :events, :bookings_count, :integer, default: 0
    Event.reset_column_information
    Event.all.each do |e|
      Event.update_counters e.id, :bookings_count => e.bookings.length
    end


  end
end

Do I need to add anything in my Events controller? I've set my Booking model up as per the Guides -

 belongs_to :event, counter_cache: true

Do I need to add anything to my Event model?

This was simply a case of poor code on my part, I used -

 <p><%= pluralize @event.bookings_count.size, 'booking' %></p>

It actually should have been -

 <p><%= pluralize @event.bookings.size, 'booking' %></p>

However, this would have still used the database to count, thus, rendering the usage of the counter_cache redundant so using this -

<p><%= pluralize @event.bookings_count, 'booking' %></p>

gives me the output I was looking for and also leveraging from counter_cache in the way intended.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM