Section 10.2.1 of the Rails Tutorial utilizes before_filter
which is deprecated. What's the modern idiomatic way to write the code in UsersController
so as to not use before_filter
?
Here's a version of edit
that I tried:
def edit
if ( signed_in? )
@title = "Edit user"
else
de开发者_StackOverflow社区ny_access
end
end
However, this triggers 2 failures in when I run rspec.
rspec ./spec/requests/friendly_forwardings_spec.rb:6 # FriendlyForwardings should forward to the requested page after signin
rspec ./spec/controllers/users_controller_spec.rb:266 # UsersController authentication of edit/update pages for non-signed-in users should deny access to 'edit'
before_filter
isn't deprecated. You may be confused because the definition was moved to AbstractController::Callbacks
from ActionController::Filters::ClassMethods
in Rails 3, but it's still very much alive and kicking.
Here it is defined, deprecation-free, in Rails 3.1:
https://github.com/rails/rails/blob/v3.1.0.rc6/actionpack/lib/abstract_controller/callbacks.rb#L80
Here's the version of edit
which doesn't depend on before_filter
and allows for the specs to pass:
def edit
if ( current_user )
@user = User.find(params[:id])
if ( current_user?(@user) )
@title = "Edit user"
else
redirect_to(root_path)
end
else
session[:return_to] = request.fullpath
redirect_to("/signin" , :notice => "Please sign in to access this page.")
end
end
The original one I posted in the question didn't incorporate correct_user
.
This answer is just to point to the right solution these days.
before_filter
is deprecated in Rails 4.2, from the release notes:
The *_filter family of methods have been removed from the documentation. Their usage is discouraged in favor of the *_action family of methods:
There is a similar question: Rails 4: before_filter vs. before_action.
Rails CallBacks - ActionController::Base
, before_action
is just a new syntax for before_filter.
However, all before_filters
are deprecated in Rails 5.0 and will be removed in Rails 5.1
It is just a name change. before_action
is more specific because it gets executed before an action.
精彩评论