直接调用多态控制器的更新方法

时间:2013-10-05 00:07:11

标签: ruby-on-rails jquery polymorphism

我正在尝试对多态模型进行ajax更新并获取错误:

undefined method 'images' for #<Image:0x007fc6517ea378>
app/controllers/images_controller.rb, line 22 

(它抱怨此行@imageable.images的{​​{1}})

当从其他模型对CRUDing实例进行CRUD时,此模型/控制器可以正常运行,但在尝试直接更新时似乎会出现此错误。

为什么在嵌套表单中使用时工作,但在直接访问时却不行?

image.rb

@image = @imageable.images.find(params[:id])

images_controller.rb

class Image < ActiveRecord::Base
  default_scope order('images.id ASC')

  attr_accessible               :asset,
                                :asset_cache, 
                                :active

  belongs_to                    :imageable, polymorphic: true

  mount_uploader                :asset, ImageUploader

  def self.default
    return ImageUploader.new
  end
end

ajax电话

class ImagesController < ApplicationController
  before_filter :load_imageable
  load_and_authorize_resource

  def new
    @image = @imageable.images.new
  end

  def create
    @image = @imageable.images.new(params[:image])

    respond_to do |format|
      if @image.save
        format.html { redirect_to @imageable, notice: "Image created." }
      else 
        format.html { render :new }
      end
    end
  end

  def update
    @image = @imageable.images.find(params[:id])

    respond_to do |format|
      if @image.update_attributes(params[:image])
        format.html { redirect_to @imageable, notice: 'Image was successfully updated.' }
      else
        format.html { render :edit }
      end
    end
  end

  def destroy
    @image = @imageable.images.find(params[:id])
    @image.destroy
  end


  private

  def load_imageable
    resource, id = request.path.split('/')[1, 2]
    @imageable = resource.singularize.classify.constantize.find(id)
  end
end

1 个答案:

答案 0 :(得分:0)

我不理解的原因以及这不起作用的原因是因为@imageable实际上是image模型所属的模型,而不是image模型本身。

作为一种解决方案,我定义了一个自定义控制器操作并对其进行了发布。

class ImagesController < ApplicationController
  before_filter :load_imageable
  skip_before_filter :load_imageable, :only => :set_active
  load_and_authorize_resource

  def set_active
    Image.find(params[:id]).update_attributes(params[:image])
    render :nothing => true, :status => 200, :content_type => 'text/html'
  end

虽然这有效但可能不是最好的解决方案,所以我愿意接受建议。