Rails 4:这个方法有什么问题?

oka*_*56k 11 ruby-on-rails ruby-on-rails-4

我正在将一个应用程序升级到Rails 4,我不能在我的生活中弄清楚这个方法有什么问题.罪犯的更新方法:

def update
  respond_to do |format|
    if @doc.articles.find_index { |a| a.changed? }
      @doc.publications.destroy_all
    end
    if @doc.update_attributes(params[:doc])
      @doc.create_activity :update, owner: current_user
      if current_user.brand.editable? && params[:editing]
        format.html { redirect_to editing_url(@doc) }
      else 
        format.html { redirect_to share_url(@doc.user.ftp, @doc) }
      end
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

单击会submit生成此错误:

ActionController::UnknownFormat in DocsController#update
Run Code Online (Sandbox Code Playgroud)

并突出显示这一行:

respond_to do |format|
Run Code Online (Sandbox Code Playgroud)

create方法工作正常,它看起来像这样:

def create
  @doc = Doc.new(params[:doc])
  respond_to do |format|
    if @doc.save
      @doc.create_activity :create, owner: current_user
      if current_user.brand.editable? && params[:editing]
        format.html { redirect_to doc_editing_url(@doc) }
      else 
        format.html { redirect_to share_url(@doc.user.ftp, @doc) }
      end
    else
      format.html { render action: "new" }
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?我完全陷入了困境.

哦,我也有这种私有方法before_action,所以不是这样的:

private

def set_document
  @doc = Doc.find(params[:id])
end
Run Code Online (Sandbox Code Playgroud)

编辑

我找到了这个准解释:

在Rails 4.0中,当操作不处理请求格式时,会引发ActionController :: UnknownFormat.默认情况下,异常通过响应406 Not Acceptable来处理,但您现在可以覆盖它.在Rails 3中,始终返回406 Not Acceptable.没有覆盖.

这让我觉得它与路线有关,但是如果我已经宣布它们是这样的话我的路线应该是默认的,是吗?

resources :docs, :except => [:new, :show] do
  get "adjust/:state" => "docs#adjust", :as => :adjust
  patch "editing" => "docs#editing", :as => :editing
  patch "reupdate/" => "docs#reupdate", :as => :reupdate
  get "pdf" => "docs#pdf", :as => :pdf
  collection { post :sort }
end
Run Code Online (Sandbox Code Playgroud)

编辑2

将JSON添加到控制器,即:

format.html { redirect_to share_url(@doc.user.ftp, @doc) }
format.json { render action: 'share', status: :created, location: @doc }
Run Code Online (Sandbox Code Playgroud)

给我一个no方法错误,似乎将我重定向回编辑页面:

Showing .../fin/app/views/docs/_form.html.erb where line #19 raised:
undefined method `covers?' for nil:NilClass
Run Code Online (Sandbox Code Playgroud)

真的不知道这里发生了什么.

ilt*_*mpo 2

一种可能的原因可能是 if@doc.update_attributes(params[:doc])返回时false更新方法中没有正在执行的格式块。

通常您会在这种情况下渲染edit动作。