0

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

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

(它在抱怨@imageable.images这条线@image = @imageable.images.find(params[:id])

此模型/控制器在从其他模型中对其实例进行 CRUDing 时完美运行,但在尝试直接更新它时似乎出现此错误。

为什么以嵌套形式使用时有效,但直接访问时无效?

图片.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

images_controller.rb

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

ajax 调用

$(document).on("click", ".toggle-image-active", function(event) {
  var id = $(this).attr("data-id");
  var currently_active = $(this).attr("data-active");
  var active = true;

  if (currently_active == "true") {
    active = false;
  }

  $.ajax({
    type: "PUT",
    dataType: "script",
    url: '/images/' + id,
    contentType: 'application/json',
    data: JSON.stringify({ resource:{active:active}, _method:'put' })
  }).done(function(msg) {
    console.log( "Data Saved: " + msg );
  });
});
4

1 回答 1

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

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

于 2013-10-06T18:00:45.263 回答