【问题标题】:Self-Referential Relationship for Record will only Create Relationship with Itself记录的自我参照关系只会与自己建立关系
【发布时间】:2019-05-12 16:34:46
【问题描述】:

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

型号

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

【问题讨论】:

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


    【解决方案1】:

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

    表格

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

    控制器

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

    【讨论】:

      猜你喜欢
      • 2012-07-16
      • 2010-11-16
      • 1970-01-01
      • 2019-05-04
      • 2018-11-20
      • 1970-01-01
      • 2014-08-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多