所以我有一个node
可以是不同类型的(a Comment
&Video
)。
我想发生的事情是,每当删除a时node
,它也应该删除其指向的基础对象-例如a Video
。
这是我的模型(为简洁起见在必要时将其截断):
Node.rb
# == Schema Information
#
# Table name: nodes
#
# id :integer not null, primary key
# name :string(255)
# family_tree_id :integer
# user_id :integer
# media_id :integer
# media_type :string(255)
# created_at :datetime
# updated_at :datetime
# circa :datetime
# is_comment :boolean
#
class Node < ActiveRecord::Base
belongs_to :family_tree
belongs_to :user
belongs_to :media, polymorphic: true
has_many :comments, dependent: :destroy
has_many :node_comments, dependent: :destroy
def is_video?
self.media_type == 'Video'
end
def comment_count
self.node_comments.count + self.comments.count
end
end
这是我的Video.rb
:
# == Schema Information
#
# Table name: videos
#
# id :integer not null, primary key
# title :string(255)
# description :string(255)
# yt_video_id :string(255)
# is_complete :boolean
# created_at :datetime
# updated_at :datetime
# reply_id :integer
# circa :datetime
#
class Video < ActiveRecord::Base
# attr_accessible :title, :description, :yt_video_id, :is_complete, :user_ids
has_many :participants, dependent: :destroy
has_many :users, through: :participants
has_one :node, as: :media, :dependent => :destroy
accepts_nested_attributes_for :node, update_only: true
def self.yt_session
@yt_session ||= YouTubeIt::Client.new(:username => YouTubeITConfig.username , :password => YouTubeITConfig.password , :dev_key => YouTubeITConfig.dev_key)
end
def self.delete_video(video)
yt_session.video_delete(video.yt_video_id)
video.destroy
rescue
video.destroy
end
end
Comment.rb
# == Schema Information
#
# Table name: comments
#
# id :integer not null, primary key
# user_id :integer
# message :text
# node_id :integer
# created_at :datetime
# updated_at :datetime
#
class Comment < ActiveRecord::Base
validates :message, presence: true
belongs_to :user
belongs_to :node
def self.search(query)
where("title like ? OR description like ?", "%#{query}%", "%#{query}%")
end
end
NodeController#Destroy
def destroy
@node.destroy
respond_to do |format|
format.html { redirect_to root_path }
format.json { head :no_content }
end
end
VideoController#Destroy
def destroy
authorize! :read, @family_tree
@video = Video.find(params[:id])
if Video.delete_video(@video)
flash[:notice] = "video successfully deleted"
else
flash[:error] = "video unsuccessfully deleted"
end
redirect_to dashboard_index_path
end
CommentController#Destroy
def destroy
@comment.destroy
respond_to do |format|
format.html { redirect_to comments_url }
format.json { head :no_content }
end
end
因此,我要做的就是只要删除节点,就希望它删除关联的视频和评论。
我尝试将其添加到我的Node.rb
模型中,但是当我点击Delete时,它返回“堆栈级别太深的错误”:
belongs_to :media, polymorphic: true, dependent: :destroy
我想你想带dependent: :destroy
出has_one :node, as: :media, :dependent => :destroy
的video.rb。然后,当在node.rb中使用此行时,不应获得无限递归:belongs_to :media, polymorphic: true, dependent: :destroy
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句