【问题标题】:can't write unknown attribute `followings_count` with has_many though association尽管关联,但无法使用 has_many 写入未知属性“followings_count”
【发布时间】:2020-03-09 18:53:04
【问题描述】:

虽然与 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 %>

【问题讨论】:

  • 喂。可能是您的单数/复数等?我喜欢 Rails 的自然语言,但有时你会遇到“follower/following/followed”这样的混乱。您可以在控制台中访问所有这些关系吗?即如果您的数据库中有示例,您可以让它返回@some_category.followings_count 吗?
  • 通常has_many_through 需要一个连接模型。 has_and_belongs_to_many 没有。看起来您正在使用某种自我参照设计。你碰巧有一个表格图吗?我在想一些事情:guides.rubyonrails.org/images/association_basics/…
  • @Beartech 我有一个加入模型。它是“以下”。我使用本指南时没有图表:bhalash.com/archives/13544808202
  • 你的关系在上面提到的控制台上是否有效?

标签: ruby-on-rails ruby ruby-on-rails-5 associations simple-form


【解决方案1】:

看起来计数器缓存正在类别表中查找名为 followings_count 的列。当你在那里时,我猜你可能也错过了followers_count。这有助于我更好地理解它https://redpanthers.co/counter-cache-how-to-get-started/

【讨论】:

  • 你是对的。现在它起作用了。虽然我没有修复它,但我只是删除了这个功能,因为我现在不需要它。谢谢。
猜你喜欢
  • 1970-01-01
  • 2021-01-14
  • 2014-01-11
  • 2019-06-28
  • 1970-01-01
  • 1970-01-01
  • 2014-11-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多