0

ポリモーフィック モデルの ajax 更新を実行しようとすると、次のエラーが発生します。

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

@imageable.images(この行の について文句を言っています@image = @imageable.images.find(params[:id]))

このモデル/コントローラーは、他のモデルからインスタンスを CRUD すると完全に機能しますが、直接更新しようとするとこのエラーが発生するようです。

ネストされた形式で使用すると機能するのに、直接アクセスすると機能しないのはなぜですか?

image.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 に答える