记录的自引用关系只会与自己建立关系

时间:2019-05-12 16:34:46

标签: ruby-on-rails ruby forms methods self-reference

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

模型

    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 %>

1 个答案:

答案 0 :(得分:0)

我发现上面概述的问题是由于未在自引用关系的两个记录之间的子对父关系中定义子项而引起的。通过分别在窗体和控制器中添加以下行,我能够定义此变量并创建所需的关系。

表格

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

控制器

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