Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Render a status code without rendering a template

I'm trying to make an ajax call to a rails (5.1.3) app. I want the targeted action in the controller to render a status code 200 and do nothing else. Here's how the action looks like.

  def some_delete_action
    respond_to do |format|
      format.js do
        render status: 200, layout: false
      end
    end
  end

The issue is that rails tries to load the template associated with that action. Since there's no such template in my app, I get a ActionView::MissingTemplate error.

How can I render the status code without having rails try to reach for the template ?

like image 468
David B. Avatar asked Nov 03 '17 10:11

David B.


People also ask

How can you tell Rails to render without a layout?

2.2. By default, if you use the :plain option, the text is rendered without using the current layout. If you want Rails to put the text into the current layout, you need to add the layout: true option and use the . text. erb extension for the layout file.

How do you render a partial?

You can render the partial view in the parent view using the HTML helper methods: @html. Partial() , @html. RenderPartial() , and @html. RenderAction() .

What is Local_assigns?

local_assigns is a Rails view helper method that you can check whether this partial has been provided with local variables or not. Here you render a partial with some values, the headline and person will become accessible with predefined value.

How should you use nested layouts in Rails?

The layouts removes code duplication in view layer. You are able to slice all your application pages to blocks such as header, footer, sidebar, body and etc. This is an example of typical web application page, almost every site has these blocks. And as a rule the body block differs on each page.


1 Answers

You could use the ActionController::Head and pass :ok as value:

# home_controller.rb
def do_nothing
  head :ok
end

# routes
get 'home/do_nothing

# request in view
<script type="text/javascript">
  $.get('<%= home_do_nothing_path %>')
</script>
like image 135
Sebastian Palma Avatar answered Oct 18 '22 08:10

Sebastian Palma