记录的自我参照关系只会与自身建立关系

Self-Referential Relationship for Record will only Create Relationship with Itself

我正在尝试创建一种方法,通过该方法用户可以将相关记录附加到现有记录,类似于用户关注其他用户的方式。但是,调用该方法时,只能在记录与其自身之间建立关系。我的代码基于 follower/following 模型,我认为问题的出现是因为该方法无法区分当前记录和被选择与之建立关系的记录。任何想法如何解决这个问题?相关代码如下...

型号

    class Ingref < ApplicationRecord
        has_many :active_relationships, class_name: "Ingrelationship",
                                    foreign_key: "child_id",
                                    dependent: :destroy
    has_many :passive_relationships, class_name: "Ingrelationship",
                                     foreign_key: "parent_id",
                                     dependent: :destroy
    has_many :children, through: :active_relationships, source: :parent
    has_many :parents, through: :passive_relationships, source: :child

    # Follows a user.
    def follow(other_ingref)
        children << other_ingref
    end

    # Unfollows a user.
    def unfollow(other_ingref)
        children.delete(other_ingref)
    end

    # Returns true if the current user is following the other user.
    def following?(other_ingref)
        children.include?(other_ingref)
    end

end 

关系控制者

class IngrelationshipsController < ApplicationController
    before_action :set_search

    def create
        ingref = Ingref.find(params[:parent_id])
        ingref.follow(ingref)
        redirect_to ingref
    end

    def destroy
        ingref = Ingrelationship.find(params[:id]).parent
        @ingref.unfollow(ingref)
        redirect_to ingref
    end
end

关系模型

class Ingrelationship < ApplicationRecord
    belongs_to :child, class_name: "Ingref"
    belongs_to :parent, class_name: "Ingref"
end

表格

<% Ingref.find_each do |ingref| %>

        <div class="col-md-2">
              <div class="caption">
                <h3 class="title" style="font-size: 14px;"> <%= ingref.name %> </h3>
                    <%= form_for(@ingref.active_relationships.build) do |f| %>
                        <div><%= hidden_field_tag :parent_id, ingref.id %></div>
                        <%= f.submit "Follow" %>
                    <% end %>
              </div>
            </div>
          <% end %>

我发现上述问题的出现是由于在自引用关系中两条记录之间的 child-parent 关系中未定义子项。通过分别在表单和控制器中添加以下行,我能够定义此变量并创建所需的关系。

表格

<%= hidden_field_tag :child_id, @ingref.id %>

控制器

current_ingref = Ingref.find(params[:child_id])