【问题标题】:Defining abilities via polymorphic associations in CanCan通过 CanCan 中的多态关联定义能力
【发布时间】:2013-01-08 15:07:51
【问题描述】:

我有以下型号:

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'

知道定义这些能力类型的正确方法吗?

【问题讨论】:

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


    【解决方案1】:

    你把那个控制器弄得一团糟,试着遵循 REST(或 CRUD)。

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

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

    【讨论】:

    • 谢谢爱德华多。您是建议我将该计算移到标准索引操作中还是完全移到其他地方?
    • 关于您的回答,我不清楚控制器中的这些行如何授权响应能力。当我运行我的ability_spec.rb 时,它仍然显示可以访问响应,即使它们的父级包含意味着它们不应该的属性。这是否与ability.rb文件中的条件分开
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多