Answer the question
In order to leave comments, you need to log in
How to remove the ability to jump to actions that work with ajax + json through the browser line?
In general, below is my code that implements the loading of the book add form using ajax and json, the problem is that if you go through the browser along the path host_hame/books/new, then the browser renders what the new action returns: Can someone
tell me how to prevent the rendering of this action when passing through a line in the browser?
index.html.erb
<%= link_to 'New Book', new_book_path, remote: true, class:"new_book" %>
<div class="lol"></div>
def new
@book = Book.new
form_html = render_to_string( :partial => 'books/form', :formats => [:html], :locals => { :book => @book } )
render :json => { :form_html => form_html }
end
$(document).on('ajax:success', '.new_book', function(e, data, textStatus, xhr) {
$('.lol').append(data.form_html)
})
def new
@book = Book.new
form_html = render_to_string( :partial => 'books/form', :formats => [:html], :locals => { :book => @book } )
respond_to do |format|
format.json { render :json => { :form_html => form_html } }
format.html { redirect_to root_path }
end
end
Answer the question
In order to leave comments, you need to log in
I think you should just change the http method from GET to POST in the router module config. This will automatically weed out most curious users.
I do not know ruby, but the algorithm is very simple.
Before the output, it is enough to check whether the request is really ajax.
Looks like your solution is here: stackoverflow.com/questions/366311/how-do-you-hand...
Such a question: in fact, why do you need it? What is the problem with displaying these jasons in the browser? Just don't link to them and regular users will never see them.
You can register in the routing (well, or something like that)
It is possible in the controller
class BooksController < ApplicationController
before_action :access_check, only:[:new]
def new
@book = Book.new
form_html = render_to_string( :partial => 'books/form', :formats => [:html], :locals => { :book => @book } )
render :json => { :form_html => form_html }
end
private
def access_check
unless request.xhr?
redirect_to :root_path
end
end
end
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question