access application_helper in before_action - ruby-on-rails

I have the following in my application_helper.rb file:
module ApplicationHelper
def require_employer_profile_for_employers(page)
if current_user.type == 'Employer'
if current_user.employer_profile
else
flash[:error] = "You must create a profile before accessing #{page}."
redirect_to new_employer_profile_path
end
end
end
end
I try calling it in my projects controller like this:
before_action "require_employer_profile_for_employers('Projects')"
but my server responds with this error:
NoMethodError (undefined method `require_employer_profile_for_employers' for #<ProjectsController:0x007fb741f82e38>):
How do I access the helper in the before_action in the projects controller?

include ApplicationHelper in your ProjectsController:
class ProjectsController < ApplicationController
include ApplicationHelper
# ...
end
Helpers are not directly accessible within a controller as opposed to view layer where they are freely accessible.

Related

NoMethodError in Admin::DashboardController#index

am new to rails, and am using active admin for a work, and i get this error whenever i open active admin dashboard
NoMethodError in Admin::DashboardController#index
undefined method `asideSection' for #<Admin::DashboardController:0x00007fc544017d70>
here is my application_conrtoller.rb
class ApplicationController < ActionController::Base
before_action :asideSection
def hhome
end
def getAsideSection
#asideSections = Page.all
end
end
how can i fix it please.
before_action :asideSection tries to call a method named asideSection.
This method does not exist.
However, you have defined a method named: getAsideSection. I presume that this is what you want to be called.
So, you could either change that to: before_action :getAsideSection, or rename the method to asideSection.
Here is how I would write it, also following the ruby style guide convention of using snake_case for variables and method names:
class ApplicationController < ActionController::Base
before_action :get_aside_sections
def home
# ...
end
private
def get_aside_sections
#aside_sections = Page.all
end
end

Rails 5 in applicationHelper an helper is visible, another not

I'm learning rails.
I'm build a simple test application, with a simple authentication scheme.
I'm using a user.role field to group the users.
In my Application Helper i have:
module ApplicationHelper
def current_user
if session[:user_id]
#current_user ||= User.find(session[:user_id])
else
#current_user = nil
end
end
def user_identity
current_user.role if current_user
end
end
Now, in my app, i can use current_user in all controllers as expected, but instead user_identity is not visible.
why?
The application_helper is used mainly to access methods in views - I don't believe it's available in a controller.
The reason your 'current_user' method appears to work is that I'm assuming you're using Devise - when you call 'current_user' it is using the Engine's method rather than your own.
To solve this, write out a new module:
module MyHelper
def current_user
if session[:user_id]
#current_user ||= User.find(session[:user_id])
else
#current_user = nil
end
end
def user_identity
current_user.role if current_user
end
end
And in the controller you're using:
class MyController < ApplicationController
include MyHelper
bla bla bla...
end
Any methods defined in MyHelper will now be available in MyController, as we've included the module in the controller
Helper modules are mixed into the view context (the implicit self in your views) - not controllers.
So you can call it from the controller with:
class ThingsController < ApplicationController
# ...
def index
view_context.user_identity
end
end
Or you can include the helper with the helper method:
class ThingsController < ApplicationController
helper :my_helper
def index
user_identity
end
end
But if you're writing a set of authentication methods I wouldn't use a helper in the first place. Helpers are supposed to be aids for the view.
Instead I would create a concern (also a module) and include it in ApplicationController:
# app/controllers/concerns/authenticable.rb
module Authenticable
extend ActiveSupport::Concern
def current_user
#current_user ||= session[:user_id] ? User.find(session[:user_id]) : nil
end
def user_identity
current_user.try(:role)
end
end
class ApplicationController < ActionController::Base
include Authenticable
end
Since the view can access any of the controllers methods this adds the methods to both contexts.

Rails Engine creating a before_filter like method for all parent controllers

I'm attempting to build a Rails Gem somewhere between Devise and CanCan. Not nearly as complex as Devise, but having views and a controller.
I've created a method to be added to the top of any controller of the parent app that needs it almost exactly like Devise's before_action :authenticate_user! and CanCan's load_and_authorize_resource
I need the method to redirect_to a path in my mounted routes if the requirements are not met.
module MyEngine
module ControllerAdditions
extend ActiveSupport::Concern
module ClassMethods
def pin_verified
current_user ||= nil
#pinned = current_user.nil? ? nil : current_user
redirect_to setup_mobiles_path unless #pinned && #pinned.verified?
end
end
end
end
and in my spec/dummy/app/controllers/users_controller.rb
class UsersController < ApplicationController
pin_verified
def index
#users = User.all
end
end
pin_verified is getting called as it's supposed to but I get the following error:
undefined local variable or method `setup_mobiles_path' for UsersController:Class
Any thoughts on how I should be doing this?
==== edit ====
I altered this now to raise a custom exception, but now I need to rescue that exception some how and redirect to the needed path.
def pin_verified
current_user ||= nil
#pinned = current_user.nil? ? nil : current_user
unless #pinned && #pinned.verified?
raise ValidatedPinExpired
end
end
I tried adding this to the ApplicationController of my gem, but it doesn't seem to be hitting Controller at all.
module MyEngine
class ApplicationController < ActionController::Base
rescue_from Exception do |exception|
Rails.logger.info "==== exception: #{exception} ===="
redirect_to setup_mobiles_path
end
end
end

No method error when calling a helper method from its controller

Should this work?
module SessionsHelper
def foobar
"hello"
end
end
class SessionsController < ApplicationController
def new
foobar
end
end
When I visit the URI that goes to session#new I get an undefined method or variable 'foobar' error. I thought helper modules were automatically included in their respective controllers?
Well, including the module from the controller did it:
module SessionsHelper
def foobar
"hello"
end
end
class SessionsController < ApplicationController
include SessionsHelper
def new
foobar
end
end
I thought this behaviour was default in rails though? That the relevant helper modules are included in their controllers?

I defined a method but still getting an error 'rails undefined method'

I'm doing an authentication application. I have this code
class UsersController < ApplicationController
def new
#user = User.new
#title = "User Sign Up"
end
def create
#user = User.new(params[:user])
sign_in_check #user
if #user.save
#flash[:status] = true
#flash[:alert] = "You have successfully signed up!!"
#sign_in_check #user
redirect_to root_path, :flash => { :success => "Welcome to the Bakeshop"}
else
#title = "User Sign Up"
render 'new'
end
end
end
This is a simple sign-up code, and whenever I try and sign up, rails returns an error:
undefined method `sign_in_check' for #<UsersController:0x68c0a90>
but I defined a method sign_in_check in my Users_helper.rb:
module UsersHelper
def sign_in_check(user)
#some stuff to enable session
end
end
Does anyone have an idea why this is happening, and how to fix it?
The reason is your method is a helper. Helpers will be available in views with matching name by default, but not open to controllers without setting.
Two ways to fix:
Allow this helper in UsersController
class UsersController < ApplicationController
helper :user #This will expose UsersHelper module to UsersController
Instead, put this method into ApplicationController. I would prefer this due to the method's nature.
Include your UserHelper in your UserController as follows and you should be able to use any methods defined within the helper.
class UsersController < ApplicationController
include UsersHelper
...
end
This is usually put in the application controller
class ApplicationController < ActionController::Base
def sign_in_check(user)
#some stuff to enable session
end
end
Helpers are used for views. If you want to use it in both - you can do that, but that doesn't sound like what you're looking for here.
just include your helper module in your controller
class UsersController < ApplicationController
helper :user
...
end
Thanks

Resources