Search code examples
ruby-on-railsrubyruby-on-rails-5associationssimple-form

can't write unknown attribute `followings_count` with has_many though association


I'm trying to use has_many though association with Rails 5. I'm getting this error when saving my "category".

ActiveModel::MissingAttributeError in CategoriesController#create

can't write unknown attribute followings_count

Following model:

class Following < ApplicationRecord  
  belongs_to :category, touch: true, counter_cache: true
  belongs_to :followed_category, counter_cache: :followers_count, class_name: 'Category'
end

Category model:

class Category < ApplicationRecord
    has_many :followings
    has_many :followed_categories, through: :followings
    
    has_many :followers, foreign_key: :followed_category_id, class_name: 'Following'
    has_many :follower_categories, through: :followers, source: :category
end

Category controller:

class CategoriesController < InheritedResources::Base
  private
    def category_params
      params.require(:category).permit(:name, :description, :display_in_navbar, post_ids: [], followed_category_ids: [])
    end
end

_form.html.rb

<%= simple_form_for(@category) do |f| %>
  <%= f.error_notification %>
  <%= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present? %>

  <div class="form-inputs">
    <%= f.input :name %>
    <%= f.association :followed_categories, as: :check_boxes %>
  </div>

  <div class="form-actions">
    <%= f.button :submit %>
  </div>
<% end %>

Solution

  • It looks like counter cache is looking for a column called followings_count on the categories table. While you are there, I am guessing you migh be missing followers_count as well. This helped me understand it a bit better https://redpanthers.co/counter-cache-how-to-get-started/