Rails form_with (remote) does not see existing template - ruby-on-rails

A rails form that posts
<%= form_with url: search_results_labours_path do |f| %>
gets processed by the controller, but fails to return the expected XHR response with
Started POST "/labours/search_results" for ::1 at 2021-02-12 10:12:46 +0100
Processing by LaboursController#search_results as JS
[...]
ActionController::UnknownFormat (LaboursController#search_results is missing a template for
this request format and variant.
request.formats: ["text/javascript", "*/*"]
request.variant: []):
Yet, the template does exist
and it calls a partial _search_results.html.erb
$("div#search_results").html("<%= j render ('labours/results') %>").css({ opacity: 0 }).fadeTo('slow',1);
def search_results
#labours = Labour.order(usercontract_id: :asc).where('time_start >= ?', params[:labour][:date_start].to_date.at_beginning_of_day ).all
index_personnel
end
Why does rails not see the template for that action?
Update
changing the form to a remote
<%= form_with(url: search_results_labours_path, local: true) do |f| %>
and processing the partial as a non partial search_results.html.erb processes entirely as expected, confirming the problem is in perceiving the existence of search_results.js.erb The file also appears, with this spelling via the console to list all files.
-rw-r--r--# 1 deploy staff 105 12 Feb 10:10 search_results.js.erb

Related

Simple_form_for not using AJAX?

I got a weird problem with my form:
= simple_form_for([#item, #item_comment], :remote => true, id: "new_item_comment", :url => item_item_comments_path(#item)) do |f|
= f.input :comment, :label => false
= f.submit "Save", :class => "btn_save left"
Which in my opinion should call:
Started POST "/de-de/items/20150423/item_comments" for 127.0.0.1 at 2015-04-23 12:29:33 +0200
Processing by ItemCommentsController#create as JSON
but instead I get it as HTML:
Started POST "/de-de/items/20150423/item_comments" for 127.0.0.1 at 2015-04-23 12:29:33 +0200
Processing by ItemCommentsController#create as HTML
It used to work but without changing these parts, it only uses HTML.
Does anyone have an idea on how to solve this?
--- Update 1 ---
I added these lines to my coffeescript:
$('form[data-remote]').submit (e)->
e.preventDefault()
$.rails.handleRemote $('form[data-remote]')
And it works but I'm not really satisfied with this solution since I don't know what caused the problem.
Usually it happened to me in 2 cases:
I had a file input on the form (which forces ruby to skip remote: true option)
I had troubles with jquery-ujs javascript file (which actually processes rails html attrs)
So please check your generated html if it has <form .... data-remote='true'..> and check that jquery-ujs (or whatever handler you want to use) is included in a page javascripts.
If you are still having troubles after this, you can put a breakpoint somewhere in jquery-ujs

Ajax request returns (406 Not Acceptable )

In my Rails app javascript template profile.js.erb don't get rendered. I get error code 406 Not Acceptable. This template is supposed to append a partial in a view star#profile. Ajax request is made by jquery infinite scroll plugin. Here is my code
.
action
def profile
#page=params[:page] ||1
#videos=Video.all(:page=>#page)
respond_to do |format|
format.js
format.html
end
end
view Stars#profile
<div id="content">
<div class="post">
<%=render 'videos'%>
</div>
profile.js.erb
$('div.post').append("<%=escape_javascript(render 'videos')%>");
routes
match "stars/profile/:page"=> "stars#profile", :via => :get
log in console
Started GET "/stars/profile?page=2" for 127.0.0.1 at 2013-06-20 00:05:58 -0500
Processing by StarsController#profile as application/JavaScript
Parameters: {"page"=>"2"}
Completed 406 Not Acceptable in 65836ms
Ajax setup
jQuery.ajaxSetup({
'beforeSend': function(xhr, settings) {
xhr.setRequestHeader("Accept", "application/javascript");
var token=$('meta[name="csrf-token"]').attr('content');
xhr.setRequestHeader('X-CSRF-Token',token );
settings['dataType'] = "javascript";
settings['contentType'] = "application/javascript";
}
});
From the log:
GET "/stars/profile?page=2" does not include .js after profile. So rails does not handle it at javascript.
GET "/stars/profile.js?page=2" should be the call..

rails routing show action nested resources

Yeah the problem is, that I created a nested resource like this:
resources :albums do
resources :elements
end
and the rake routes command displays:
album_element GET /albums/:album_id/elements/:id(.:format) elements#show
So when I am at
.../albums/1
I can head for
.../albums/1/elements
This starts the index action of the elements controller, just fine.
But if I edit the index.html.erb to
<%= link_to 'Show', album_element_path %>
I got an error like this:
Started GET "/albums/1/elements" for 176.221.47.67 at Tue Oct 09 14:25:39 +0200 2012
Processing by ElementsController#index as HTML
Parameters: {"album_id"=>"1"}
Rendered elements/index.html.erb within layouts/application (9.2ms)
Completed 500 Internal Server Error in 123ms
ActionController::RoutingError (No route matches {:controller=>"elements", :action=>"show"}):
app/views/elements/index.html.erb:29:in `_app_views_elements_index_html_erb___13604879__168097178'
app/views/elements/index.html.erb:18:in `each'
app/views/elements/index.html.erb:18:in `_app_views_elements_index_html_erb___13604879__168097178'
app/controllers/elements_controller.rb:7:in `index'
So it says that no route matches ... but I actually have that in my rake routes displayed ?
What am I doing wrong ?
You need to provide the two neccesary arguments for album_element_path:
<%= link_to 'Show', album_element_path(#album, #element) %>

Why is the wrong action processing my .ajax request.

This is an issue I have been working around for some time now thinking I would eventually stumble on an explaination. I have not and it's now becoming a little more problematic for me.
I used rails-generate-scaffold to create a simple (users and posts) application. This was done after installing jquery and jquery-ui. I added actions "login" and "auth" to the users controller. Login.html.erb contains some javascript that sends .ajax request to the users#auth action passing the login information (email and password) as parameters.
The the template auth.js.erb exists. The "auth" action responds to format.js. The request looks normal, but rails processes the request with the "show" action rather than the "auth" action.
In other words, a request to userscontrollers#auth (via .ajax) is being processed by userscontroller#show (as JS).
The problem goes away if I remove the "resources :users" route that scaffold added (the correct action is then called). But without this route other useful scaffold stuff becomes unuseable (like users#new).
From Gemfile: gem 'jquery-rails', '>=0.2.6'
Installed jQuery with: rails generate jquery:install --ui
From ../layouts/application.html.erb
<head>
<title>Tab1</title>
<%= stylesheet_link_tag :all %>
<%= stylesheet_link_tag 'jquery-ui-1.8.16.custom.css' %>
<%= javascript_include_tag :defaults %>
<%= javascript_include_tag 'jquery.min.js' %>
<%= javascript_include_tag 'jquery.min.js', 'jquery-ui.min.js' %>
<%= csrf_meta_tag %>
</head>
Here is ./log/development.log to shows the request and the response.
Started GET "/users/auth/?email=steve&password=[FILTERED]&_=1326063255777" for 24.11.242.181 at 2012-01-08 17:53:45 -0500
Processing by UsersController#show as JS
Parameters: {"email"=>"steve", "password"=>"[FILTERED]", "_"=>"1326063255777", "id"=>"auth"}
^[[1m^[[36mUser Load (0.2ms)^[[0m ^[[1mSELECT `users`.* FROM `users` WHERE `users`.`id` = 0 LIMIT 1^[[0m
Completed 404 Not Found in 6ms
ActiveRecord::RecordNotFound (Couldn't find User with ID=auth):
app/controllers/users_controller.rb:43:in `show'
Suggests that the request --> GET "/users/auth/?email ... is being processed by UsersController#show as JS
Thanks

Error during failsafe response: Ruby on Rails 3

I have a form_tag that works fine using html, but when I use ajax with the remote => true I am getting this error:-
My terminal log shows:-
Started GET "/" for 127.0.0.1 at 2010-11-01 01:19:49 +0000
Processing by HomepagesController#index as HTML
Homepage Load (0.6ms) SELECT "homepages".* FROM "homepages"
Rendered homepages/index.html.erb within layouts/application (23.0ms)
Completed 200 OK in 40ms (Views: 27.3ms | ActiveRecord: 0.6ms)
Error during failsafe response: incompatible encoding regexp match (UTF-8 regexp with ASCII-8BIT string)
* then a load of cleaner.rb stuff
then:-
Started GET "/homepages?utf8=%E2%9C%93&search=hom" for 127.0.0.1 at 2010-11-01 01:19:56 +0000
Processing by HomepagesController#index as JS
Parameters: {"utf8"=>"✓", "search"=>"hom"}
Homepage Load (0.5ms) SELECT "homepages".* FROM "homepages" WHERE (section LIKE '%hom%')
Rendered homepages/index.js.erb (2.9ms)
Completed in 19ms
In my index.js.erb I have:-
$("testsearch").update("<%= escape_javascript(render(#homepages))%>");
and in my Controller I have:-
def index
#homepages = Homepage.search(params[:search])
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #homepages }
format.js { render :layout => false }
end
in my view I have:-
which prints #homepages using a table using <% #homepages.each do |homepage| %> which is not being updated.
Anyone have any ideas as to why I get this error.
I have cracked it by going onto an IRC chat room (irc.freenode.net RubyonRails) and a ProjectZen (human being somewhere out there in the ether) helped me to get it working.
Apparently what was happening was that I was following Ryan Bates who does many extremely good Railcast videos, but he builds on previous Railcast. Therefore in his 205 Railscast, which deals with Ajax calls, he did not mention that you must have:-
format.js in the action in the controller.
His xxxx.searchxxxxx needs to be created in the controller or model.
And that when I did :-
<%= render(#homepages)%> <!-- (in his case <%= render(#products)%>) -->
The render was looking for a partial called "_homepage" (not "homepages") (I did not even have a partial therefore I got the UTF8 to ASCII error).
And then in "_homepage" I would add my code to render the results.
What I have now done in my index.html.erb is to put <%= render(#homepages)%>, in the (div id = testsearch) in place of the code I use to render #homepages and then place that code in a partial "_homepage". Now I can use "_homepage" for the html and the Ajax call.
At the moment I have a slight problem in that it is rendering all the data in the"#homepages" as many times as the number of records. At the moment I do not know why, but at least the Ajax call is working.

Resources