You can create controller actions that you reference. For example, in an application, I have the following two actions added to a user controller. Once the routes are also configured, I use URL helpers to reference actions from my view and ultimately output flash messages via javascript callbacks.
UsersController:
def follow @user = User.find(params[:id]) if current_user if current_user == @user flash[:error] = "You cannot follow yourself." else current_user.follow(@user) RecommenderMailer.new_follower(@user).deliver if @user.notify_new_follower flash[:notice] = "You are now following #{@user.monniker}." end else flash[:error] = "You must <a href='/users/sign_in'>login</a> to follow #{@user.monniker}.".html_safe end end def unfollow @user = User.find(params[:id]) if current_user current_user.stop_following(@user) flash[:notice] = "You are no longer following #{@user.monniker}." else flash[:error] = "You must <a href='/users/sign_in'>login</a> to unfollow #{@user.monniker}.".html_safe end end
config / route.rb:
resources :users do member do get :follow get :unfollow end end
Then, in your opinion, you can use the URL helper to refer to the controller action:
<%= link_to "Unfollow", unfollow_user_path(@user) %>
Jutil source share