I have a model AdminUser, a folder admin_users in my views with 2 views only (dashboard and index), and an AdminUsersController which is:
class AdminUsersController < ApplicationController
def dashboard
end
def index
end
def login
if params[:admin_user][:username].present? && params[:admin_user][:password].present?
found_user = AdminUser.where(:username => params[:admin_user][:username]).first
if found_user
authorized_user = found_user.authenticate(params[:admin_user][:password])
session[:admin]=params[:admin_user][:username]
end
end
if authorized_user
redirect_to :controller => 'admin_users', :action => 'dashboard'
else
render :nothing => true, :status => :ok
end
end
end
Although I have an action for login, I do not have a view for it, because I don't really need it.
But the fact that Rails searches for a view make me think that I am doing something wrong; or at least not doing something the Rails-y way.
Should I do this in another way?
You are not required to have a view. In fact quite a few good reasons exist to not need a view:
The conventions are there for the most common circumstances, but there are also conventions for lesser common, and still valid situations.
Note that methods that are not intended to be renderable actions should be placed in the protected or private section of the class to keep them separated from actual actions. Don't expose any methods in the public interface of the controller, except those that are intended to be actions.
If you do happen to have an action (as does the example in the question), you can convince Rails to bypass the search for a view corresponding to the action by returning early. While it would seem like redirect_to would be sufficient, it's actually only part of the response. The common way to do this is use the redirect_to :page and return idiom.
For the example given, use this:
if authorized_user
redirect_to :controller => 'admin_users', :action => 'dashboard' and return
else
render :nothing => true, :status => :ok
end
See these excellent questions and answers for more detail:
Not having a view is completely fine. When you add methods to your controller that you don't want views for, such as create/update/destroy methods, you'll notice you need to add a "render" or "redirect_to" statement within that method that points to another view. This tells rails not to follow the norm and look for a view with that actions name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With