Ruby on rails Rails 4:如何检查实例是否已被删除
在Rails应用程序中,我们有一个Ruby on rails Rails 4:如何检查实例是否已被删除,ruby-on-rails,ruby-on-rails-4,model-view-controller,destroy,Ruby On Rails,Ruby On Rails 4,Model View Controller,Destroy,在Rails应用程序中,我们有一个日历控制器: class CalendarsController < ApplicationController def create @calendar = current_user.calendars.create(calendar_params) current_user.add_calendar_and_role(@calendar.id, 'Owner') if @calendar.save curren
日历控制器
:
class CalendarsController < ApplicationController
def create
@calendar = current_user.calendars.create(calendar_params)
current_user.add_calendar_and_role(@calendar.id, 'Owner')
if @calendar.save
current_user.total_calendar_count += 1
current_user.owned_calendar_count += 1
current_user.save
flash[:success] = "Calendar created!"
redirect_to dashboard_path
else
render 'static_pages/home'
end
end
def show
@calendar = Calendar.find(params[:id])
@posts = @calendar.posts
@post = Post.new
end
def index
end
def edit
end
def destroy
Calendar.find(params[:id]).destroy
flash[:success] = "Calendar deleted"
redirect_to dashboard_path
end
private
def calendar_params
params.require(:calendar).permit(:name)
end
end
此代码的语法是否正确,尤其是if@calendar.delete
和if@calendar.administrations.role==“Owner”
而且,最重要的是,这个
销毁行动的代码有意义吗?我相信它更像是:
def destroy
@calendar = Calendar.find(params[:id])
calendar_admin_role = @calendar.administrations.role
if @calendar.destroy
flash[:success] = "Calendar deleted"
current_user.total_calendar_count -= 1
if calendar_admin_role == "Owner"
current_user.owned_calendar_count -= 1
end
end
redirect_to dashboard_path
end
但是,在工作了一整天之后,这已经超出了我的想象,所以可能是错误的。你想过使用持久化方法吗?
方法
@calendar.destroy
unless @calendar.persisted?
... some code here ....
end
好的,谢谢。仅供我参考,为什么在action
方法中,我们使用if@calendar.save
而不是``if@calendar.create,但是在destroy`方法中,我们使用if@calendar.destroy
而不是if@calendar.delete
。很抱歉,如果这是一个愚蠢的问题,我对Ruby&Rails还很陌生,对此我有点困惑。在这种情况下,使用@calendar=calendar.build(calendar\u params)
,可能更像是“Rails”,然后使用if@calendar.save
build
不会在数据库中创建任何内容,save
会这样做<代码>删除
与销毁
不同。它删除对象而不运行它们的回调。看,不,我没有。其他代码结构的优点是什么?这是Rails的方法吗?坚持?检查您的记录是否仍在数据库中或仅在内存中。如果它没有在数据库中“持久化”,它将返回“false”。这就是你想做的。这是一种Rails ActiveRecord方法:听起来确实像我们想要实现的,非常感谢。没问题!请检查我的答案是否正确,这样我将获得一些魔力:D
@calendar.destroy
unless @calendar.persisted?
... some code here ....
end