Declarative Auth blocking instance variables - ruby-on-rails

I'm using declarative authorization in my rails app, and I have the following controller:
class OrganizationsController < ApplicationController
filter_resource_access attribute_check: true
def index
#organizations = Organization.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #organizations }
end
end
end
However when I try to access the view for that action, I get the error
undefined method 'each' for nil:NilClass on the line where I try to access the #organizations instance variable. It works when I comment out the filter_resource_access line.
Any thoughts?

the error is because your instance variable is Nil, is why it says undefined method each for nil:NilClass. filter is a method that runs either before or after the controller, in this case i'm not exactly sure what that method means but its not letting you access the data until after the controller is my guess.

Apparently I forgot to include the declarative_authorization gem in my Gemfile. :shame:
All is working now.

Related

Ruby/Rails: Why is render json: {hello: 'world'} hitting my database?

I have an action:
def test
_process_action_callbacks.map { |c| pp c.filter }
render json: {hello: 'world'}
end
That for some reason is calling my current_user function defined in my application controller.
At first I thought it was a before action that was calling my current_user function (hence _process_action_callbacks). But after stripping away all of my before actions the call remained. The only two before actions are part of rails:
:clean_temp_files
:set_turbolinks_location_header_from_session
I used caller to see where my method was getting called from. Here's the stacktrace (and method declaration):
def current_user
pp caller
# get the current user from the db.
end
As you can see, the current_user function is being called by the serialization_scope method in the serialization class. How do I prevent it from calling my current_user function?
Your tag indicates you are using active-model-serializers. By default current_user is the scope. To customize the scope, defined in the application-controller, you can do something like
class ApplicationController < ActionController::Base
serialization_scope :current_admin
end
The above example will change the scope from current_user (the default) to current_admin.
In your case, you probably just want to set the scope in your controller (I assume it is called SomeController ;) ) you can write
class SomeController < ApplicationController
serialization_scope nil
def test
render json: {hello: 'world'}
end
end
See for complete documentation: https://github.com/rails-api/active_model_serializers/tree/0-9-stable#customizing-scope

calling render raises "Undefined method 'logger' for true class"

I'm at a loss trying to figure out what is causing this issue. If I call any variation of render in my controller it raises the following:
NoMethodError: undefined method `logger' for true:TrueClass
from /Users/username/.rvm/gems/ruby-2.3.4/gems/activesupport-5.1.3/lib/active_support/configurable.rb:113:in `logger'
I checked active_support/configurable.rb:113 and I don't quite understand what it's comparing and raising for. I have other controllers that which both share the same base controller, that is not throwing this error when I render.
What am I not seeing here?
EDIT
Calling render from
class Device::V1::DeviceController < ApplicationController
def status
render json: { foo: 'bar' }, status: :ok
end
end
Below is my application controller
class ApplicationController < ActionController::API
include ActionController::HttpAuthentication::Token::ControllerMethods
before_action :authenticate!
private
def authenticate!
authenticate_or_request_with_http_token do |token, options|
token == SECRET[:api_key]
end
end
end
Rails 5.1.3
Ruby 2.3.4
UPDATE
I had a method in this controller called config. Apparently this is a reserved namespace that conflicted with ActiveSupport
I had a controller method named config. This is a reserved name.

after_initialize never invoked in Rails 3 via mixin

I am using a mixin to add some functionality to my model (Person). In the mixin I need some initializations to be done so I am trying to use the "after_initialize" callback macro to invoke an initialization method. The model (Person) is only a base class for some other models.
The problem I am having is that it gets never called. I tried to debug it but the breakpoint never got hit. Also logging gives me no output.
I couldn`t find any help (as this construct should be working in Rails 3 according to the Api docs and some posts here).
/lib/mymodule.rb
module MyModule
after_initialize :generate_ids
def generate_ids
logger.info "invoked" #never hit
end
end
/models/person.rb
require "mymodule"
class Person < ActiveRecord::Base
include MyModule
end
/models/customer.rb
class Customer < Person
# nothing so far
end
*/controllers/customers_controller.rb (action => new)*
# GET /customers/new
# GET /customers/new.json
def new
#person = Customer.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #customer }
end
end
Please be indulgent to me as I am a "newbie" to RoR.
Thank you very much !
Best regards,
Thomas
UPDATE
After restarting the local app server it gives me the following exception:
ActionController::RoutingError (undefined method `after_initialize' for SequentialRecord:Module):
I assume this callback can`t be used in mixins ?
Try something like that (not tested).
module MyModule
def self.included(base)
base.after_initialize :generate_ids
end
def generate_ids
logger.info "invoked" #never hit
end
end

ActiveAdmin: How to override index controller action: undefined method `base' for nil:NilClass

I'm trying to override the index action of the ActiveAdmin controller for it to display results for the current_user instead of all results.
controller do
def index
#user_tasks = UserTask.where(:user_id => current_user.id).page(params[:page])
end
end
When accessing ActiveAdmin, an exception in thrown:
ActionView::Template::Error (undefined method `base' for nil:NilClass):
1: render renderer_for(:index)
I'm using rails 3.1 and the latest ActiveAdmin version. gem "activeadmin", :git => 'https://github.com/gregbell/active_admin.git'.
I don't know why but
controller do
def index
index! do |format|
#user_tasks = UserTask.where(:user_id => current_user.id).page(params[:page])
format.html
end
end
end
did the trick.
This is not required any more.
ActiveAdmin 0.4.4 now supports scoping queries without overriding this method.
please see here: http://activeadmin.info/docs/2-resource-customization.html#scoping_the_queries
If your administrators have different access levels, you may sometimes
want to scope what they have access to. Assuming your User model has
the proper has_many relationships, you can simply scope the listings
and finders like so:
ActiveAdmin.register Post do
scope_to :current_user
# or if the association doesn't have the default name.
# scope_to :current_user, :association_method => :blog_posts
end
Let override the action like this:
controller do
def scoped_collection
# some stuffs
super.where("type = ?", "good")
end
# other stuffs
end
By this way, you also can run the export functions (to xml, csv, ...) normally with new collection that you have overridden.
In my test, it just works for where condition and scope, not for limit.
Refer from this: https://github.com/activeadmin/activeadmin/issues/642

Active admin layout was lost after overriding Controller action

My new controller action:
controller do
layout 'active_admin'
def index
#pages = Page.all
end
end
After refresh the page i received:
undefined method `base' for nil:NilClass
render view_factory.layout
What should I do for fixing this?
I start rewriting controller action because i received this message for my index action:
undefined method `num_pages' for #<Array:0x0000000b860eb0>
render renderer_for(:index)
Maybe anyone know how fixing this?
The initial undefined method 'num_pages' for #<Array:0x0000000b860eb0> may be occurring if you have an instance variable set in a before_filter in ApplicationController with the plural name of a model as I did. The bug is reported here.
Would need to see the code on the view page for this but it sounds to me like you are making a call for num_pages on an object that is an array class. Since Ruby's array class has no num_pages method, it is throwing an error.
Jamie you are right! But then i received this message for my index action:
undefined local variable or method `per' for ActiveRecord::Relation
And I fix this problem by doing this:
# config/initializers/will_paginate.rb
if defined?(WillPaginate)
module WillPaginate
module ActiveRecord
module RelationMethods
alias_method :per, :per_page
alias_method :num_pages, :total_pages
end
end
end
end
The bug is reported here.

Resources