【发布时间】:2021-05-13 13:48:17
【问题描述】:
我正在与您联系,因为我有一个相当重要的问题。而且尽管我对 stackoverflow 或其他地方进行了研究,但经过大量测试和大量修补后,我无法纠正。
我通过创建一个可以列出我称之为“八卦”的秘密的网站来练习。
有一个按钮可以让你删除“八卦”。
但是当我想删除“八卦”时
据我了解,是我的表之间的关系导致了问题。因此,我在问题中附上这些表格的代码:
class Tag < ApplicationRecord
has_many :gossips, through: :tag_join_gossip, dependent: :destroy
validates :title, presence: true
end
class TagJoinGossip < ApplicationRecord
belongs_to :gossip
belongs_to :tag, optional: true
end
class Gossip < ApplicationRecord
belongs_to :user, optional: true
has_many :likes
has_many :tags, through: :tag_join_gossip
has_many :comments
validates :title, presence: true, length: {minimum: 3, maximum: 14}
validates :content, presence: true, length: {minimum: 1}
end
我的控制器:
class GossipController < ApplicationController
before_action :authenticate_user
def index
@id = params[:id]
@gossips = Gossip.all
end
def show
@id= params[:id]
@gossip = Gossip.find(params[:id])
@comments = Gossip.find(params[:id]).comments
@comment = Comment.new(content: params['content'], gossip_id: 1, gossip_id: @gossip ,user_id: 1)
end
def new
@gossip = Gossip.new
end
def create
@gossip = Gossip.new(title: params['title'], content: params['content'])
@gossip.user = User.find_by(id: session[:user_id])
if @gossip.save
flash[:success] = "Gossip bien créé!"
redirect_to welcome_index_path
else
flash[:danger] = "Nous n'avons pas réussi à créer le potin pour la (ou les) raison(s) suivante(s) "
render new_gossip_path
end
end
def edit
@gossip = Gossip.find(params[:id])
end
def update
@gossip = Gossip.find(params[:id])
gossip_params = params.require(:gossip).permit(:title, :content)
if @gossip.update(gossip_params)
flash[:success] = "Gossip bien modifié !"
redirect_to welcome_index_path
else
render :edit
flash[:danger] = "Nous n'avons pas réussi à modifier le potin, le titre doit faire 3 lettres minimum et vous devez remplir le contenu."
end
end
def destroy
@gossip = Gossip.find(params[:id])
@gossip.destroy
redirect_to welcome_index_path
end
end
private
def authenticate_user
unless current_user
flash[:danger] = "Veuillez vous connecter."
redirect_to new_session_path
end
end
也许还有其他感兴趣的文件,所以我把我项目的 github 放在这里:https://github.com/MC4517/Projet-THP-GOSSIP-J1
我已经玩了一整天了,我开始失去理智了,哈哈。
非常感谢那些冒险解决我的问题的人,尽管我认为这对你们中的大部分人来说一定很容易!
【问题讨论】:
标签: ruby-on-rails ruby activerecord foreign-keys