Rails 与自身的关联不起作用

Posted

技术标签:

【中文标题】Rails 与自身的关联不起作用【英文标题】:Rails association with itself not working 【发布时间】:2020-03-09 14:44:58 【问题描述】:

我不断收到此错误

ActiveRecord::RecordNotFound in CategoriesController#create 不能 查找与 'id'=[4] 的关系

我的架构:

  create_table "relationships", force: :cascade do |t|
    t.integer "follower_id"
    t.integer "followed_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["followed_id"], name: "index_relationships_on_followed_id"
    t.index ["follower_id", "followed_id"], name: "index_relationships_on_follower_id_and_followed_id", unique: true
    t.index ["follower_id"], name: "index_relationships_on_follower_id"
  end

  create_table "categories", force: :cascade do |t|
    t.string "name"
    t.text "description"
    t.boolean "display_in_navbar", default: true
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

我的类别表单

<%= f.input :name %>
<%= f.input :description %>
<%= f.association :active_relationships, collection: Category.order(:name), prompt: "Choose a Category" %>

类别型号:

class Category < ApplicationRecord
    has_and_belongs_to_many :posts

    has_many :active_relationships, class_name:  "Relationship",
                                    foreign_key: "follower_id",
                                    inverse_of: :follower,
                                    dependent: :destroy
    has_many :passive_relationships, class_name: "Relationship",
                                    foreign_key: "followed_id",
                                    inverse_of: :followed,
                                    dependent: :destroy
    has_many :following, through: :active_relationships, source: :followed
    has_many :followers, through: :passive_relationships, source: :follower

end

关系模型:

class Relationship < ApplicationRecord
  belongs_to :follower, class_name: "Category"
  belongs_to :followed, class_name: "Category"

  validates :follower_id, presence: true
  validates :followed_id, presence: true
end

类别控制器:

class CategoriesController < InheritedResources::Base

  private

    def category_params
      params.require(:category).permit(:name, :description, :display_in_navbar, post_ids: [], active_relationship_ids: [])
    end

end

【问题讨论】:

【参考方案1】:

尝试将值方法和标签方法显式添加到集合输入

<%= f.association :active_relationships, collection: Category.order(:name).all.map|cat| [cat.name, cat.id], label_method: :first, value_method: :last, prompt: "Choose a Category" %>

【讨论】:

以上是关于Rails 与自身的关联不起作用的主要内容,如果未能解决你的问题,请参考以下文章

Rails 关联不起作用,user_id 未显示在控制台中

Has_many:通过 Rails 4 实例变量不起作用

使用dependent: :destroy 在rails 上不起作用

带有has_many的模型中的属性总和:通过关联在Rails 5中不起作用

直接使用分页器并在关联列上定义排序不起作用

Rails 渲染不起作用