Displaying a view of a controller action from around_action callback

I am showing a bit of js.erb that allows the ajax function to like / dislike a dish in a restaurant. I recently ran into a callback around_action , and the yield figure helped to first execute the controller action and display the second template. Unfortunately, I get 500 (Internal Server Error) due to the fact that respond_to never called.

The respond_to method works if I put it inside the controller action, but not inside the callback. What am I doing wrong?

 class DishesController < ApplicationController before_action :set_dish_and_restaurant around_action :render_vote_partial def like @dish.liked_by current_user end ... private def set_dish_and_restaurant @dish = Dish.find(params[:id]) end def render_vote_partial yield respond_to { |format| format.js { render "vote.js.erb" } } end end 

Console error

 ActionView::MissingTemplate (Missing template dishes/like, application/like with {:locale=>[:en], :formats=>[:js, "application/ecmascript", "application/x-ecmascript", :html, :text, :js, :css, :ics, :csv, :vcf, :png, :jpeg, :gif, :bmp, :tiff, :mpeg, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json, :pdf, :zip], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}. Searched in: * "/app/views" * "/Library/Ruby/Gems/2.0.0/gems/devise-3.5.1/app/views" ): app/controllers/dishes_controller.rb:29:in `render_vote_partial' 
+4
source share
1 answer

Okay, so with your stack trace it's pretty clear what happens. You must understand the default behavior of rails compared to configuration.

As soon as you call yield , you call the controller action. Now all controller actions look by default to render views with the same name as the action after the actions are completed.

So calling render_to after yield does not make any sense, because the action of the controller that you gave already caused its visualization :)

In any case, what you are trying to do is a bad design pattern, rendering of views should be left to actions

Update

Theoretically: since you want to keep DRY stuff, you can display the same view after each action by creating a common method that calls it after each action. However, think about it, your render will have one line, and to call the same method you will need one line :), so somewhere DRY.

In short, DRY should not be done at the expense of simplicity. In my opinion KISS trump cards DRY :)

+1
source

All Articles