我正在尝试对多态模型进行 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 );
});
});