не может написать неизвестный атрибут `followings_count` с has_many, хотя ассоциация - PullRequest
1 голос
/ 09 марта 2020

Я пытаюсь использовать has_many, хотя и связан с Rails 5. Я получаю эту ошибку при сохранении моей "категории".

ActiveModel :: MissingAttributeError в CategoriesController # create

невозможно записать неизвестный атрибут followings_count

Следующая модель:

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

Модель категории:

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

Контроллер категории:

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 %>

1 Ответ

0 голосов
/ 10 марта 2020

Похоже, что кеш счетчика ищет столбец с именем followings_count в таблице категорий. Пока вы там, я думаю, вы тоже можете пропустить followers_count. Это помогло мне понять это немного лучше https://redpanthers.co/counter-cache-how-to-get-started/

...