Rails 4:如何检查实例是否已被删除

时间:2015-07-09 16:25:00

标签: ruby-on-rails ruby-on-rails-4 model-view-controller destroy

在我们的Rails应用中,我们有CalendarsController

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

create操作中,当创建新的@calendar时,我们运行@calendar.save以检查是否实际创建了新实例,然后执行某些操作。

我们希望在destroy行动中实施类似的流程。

我们正在考虑更新destroy方法,如下所示:

def destroy
  @calendar = Calendar.find(params[:id])
  @calendar.destroy
  if @calendar.delete
    flash[:success] = "Calendar deleted"
    current_user.total_calendar_count -= 1
    if @calendar.administrations.role == "Owner"
      current_user.owned_calendar_count -= 1
    end
  end
  redirect_to dashboard_path
end

此代码的语法是否正确,尤其是if @calendar.deleteif @calendar.administrations.role == "Owner"

最重要的是,这个destroy行为的代码是否有意义?

2 个答案:

答案 0 :(得分:1)

我相信它更像是:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/oldsite/$1 -f [OR]
RewriteCond %{DOCUMENT_ROOT}/oldsite/$1 -d
RewriteRule ^(.*)$ /oldsite/$1 [L]

但经过漫长的一天工作后,这是我的头脑,所以可能是错的。

答案 1 :(得分:1)

您是否考虑过使用persisted?方法

@calendar.destroy
unless @calendar.persisted?
   ... some code here ....
end