我正在尝试创建一种方法,通过该方法,用户可以将相关记录附加到现有记录,类似于用户可以关注其他用户的方式。但是,当调用该方法时,只能在记录和其自身之间建立关系。我将我的代码建立在关注者/关注者模型上,我认为问题的出现是因为该方法无法区分当前记录和选择要创建关系的记录。有什么想法可以解决这个问题吗?相关代码如下...
模型
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 %>
发布于 2019-05-14 03:11:56
我发现上面概述的问题是由于在自我引用关系中的两个记录之间的子代-父代关系中没有定义子代。通过在表单和控制器中分别添加以下行,我能够定义此变量并创建所需的关系。
表格
<%= hidden_field_tag :child_id, @ingref.id %>
控制器
current_ingref = Ingref.find(params[:child_id])
https://stackoverflow.com/questions/56101266
复制相似问题