【发布时间】: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