通过CanCan中的多态关联定义能力

时间:2013-01-08 15:07:52

标签: ruby-on-rails ruby-on-rails-3.2 cancan polymorphic-associations rails-activerecord

我有以下型号:

class Post < ActiveRecord::Base
   has_many :responses, as: :responseable, dependent: :destroy
end

class Call < ActiveRecord::Base
   has_many :responses, as: :responseable, dependent: :destroy
end

class Meeting < ActiveRecord::Base
   has_many :responses, as: :responseable, dependent: :destroy
end

class Response < ActiveRecord::Base
   belongs_to :responseable, polymorphic: true # Tested
end

在CanCan中,我试图通过多态关联中的属性来定义特定自定义响应操作的功能。行动如下:

class ResponsesController < ApplicationController

  before_filter :authenticate_user!
  load_and_authorize_resource

  respond_to :html, :xml, :js, :json, :pdf


  # GET /responses/polling
  # GET /responses/polling.json
  def polling
    responseable_type = params[:responseable_type]
    klass = [Post, Call, Meeting].detect { |c| responseable_type}
    @responseable = klass.find(params[:responseable_id])
    undivided_millisecond_epoch_time_in_integer = params[:after]
    undivided_millisecond_epoch_time_in_decimal = (undivided_millisecond_epoch_time_in_integer).to_d
    divided_millisecond_epoch_time_in_decimal = (undivided_millisecond_epoch_time_in_decimal / 1000000).to_d
    @responses = @responseable.responses.where("created_at > ?", Time.at(divided_millisecond_epoch_time_in_decimal))
  end
...

此操作通过javascript函数运行,该函数每5秒轮询一次新响应。但是,当运行时,我在日志中遇到以下错误:

A NameError occurred in responses#polling:

  uninitialized constant Responseable
  activesupport (3.2.8) lib/active_support/inflector/methods.rb:230:in `block in constantize'

是否有正确的方法来定义这些类型的能力?

1 个答案:

答案 0 :(得分:1)

你在那个控制器上弄得一团糟,试着跟着REST(或CRUD)。

无论如何,Cancan无法检测到您尝试授权的资源。尝试这样的事情:

load_resource :post
load_resource :call
load_resource :meeting
load_and_authorize_resource :response, :through => [:post, :call, :meeting]