无法通过关联将具有has_many的未知属性`followings_count`

问题描述 投票:1回答:1

我试图通过与Rails 5的关联来使用has_many。保存“类别”时出现此错误。

CategoriesController#create中的ActiveModel :: MissingAttributeError

无法写未知属性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 %>
ruby-on-rails ruby ruby-on-rails-5 associations simple-form
1个回答
0
投票

似乎计数器缓存正在类别表上寻找名为followings_count的列。当您在那里时,我想您也可能会错过followers_count。这有助于我更好地理解它https://redpanthers.co/counter-cache-how-to-get-started/

© www.soinside.com 2019 - 2024. All rights reserved.