【发布时间】: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