I'm trying to display a flash message when I clicked the "check" button without re-rendering the entire page.
In the development mode, the code below does work but doesn't in the production mode.
Instead of staying in the main.html and displaying the flash message, it redirect me to "check" page.
The log console gave me debug messages below:
Completed 406 Not Acceptable in 2ms (ActiveRecord: 0.0ms)
ActionController::UnknownFormat (ActionController::UnknownFormat):
app/controllers/my_controller.rb:105:in `check'
Did I miss something for working on production mode?
main.html.erb
<div class="check"><%= render partial: 'check' %></div>
<%= f.submit :Check, class: "btn btn-default", remote: true, formaction: app_check_path %>
_check.html.erb
<div id = "notice">
</div>
check.js.erb
$("#notice").html('<p style="color: green;"><%= flash[:notice] %></p>').show().delay(5000).hide(0);
my_controller.rb
def check
notice = "NOTICE!"
respond_to do |format|
format.js do
flash[:notice] = notice
end
end
end
routes.rb
get 'app/check'
post 'app/check'
Try to the following
_check.html.erb
<% flash.each do |msg| %>
<%= msg.html_safe %>
<% end %>
check.js.erb
$("#notice").html('<%= escape_javascript(render("check")) %>');
my_controller.rb
Change this line
notice = "<p style='color: green;'>NOTICE!</p>"
Hope to help
You need to submit your form in JS format in order to render a JS type response!
Related
I would like to use Ajax to add a micropost to my home page without redirect as soon as it is created. I added remote: true in the form:
<%= form_for(#micropost, html: { multipart: true }, remote: true) do |f| %>
and edited the create action of the microposts controller as follows:
def create
#micropost = current_user.microposts.build(micropost_params)
microposts_number = current_user.microposts.where("created_at >= ?", Time.zone.now.beginning_of_day).count
if microposts_number < 10
if #micropost.save
respond_to do |format|
format.html do
flash[:success] = "Micropost created!"
redirect_to root_url
end
format.js
end
else
#feed_items = []
flash[:danger] = #micropost.errors.full_messages.join(', ')
render 'static_pages/home'
end
else
flash[:danger] = "You have exceeded your daily share of microposts (10)."
redirect_to root_url
end
end
The microposts are shown in the home page as orded list of items, where #feed_items is a collection of microposts for current_user, thus belonging to Micropost:
<% if #feed_items.any? %>
<ol class="microposts">
<%= render #feed_items %>
</ol>
<%= will_paginate #feed_items %>
<% end %>
Therefore I created app/views/microposts/create.js.erb, using jQuery to select ol.microposts and function prepend() to add the newly created micropost to the page:
$("ol.microposts").prepend('<%= escape_javascript(render partial: #micropost) %>');
The partial _micropost.html.erb, used to build the li elements inside ol.microposts is (simplified) below:
<li id="micropost-<%= micropost.id %>">
<%= link_to gravatar_for(micropost.user, size: 50), micropost.user %>
<span class="user"><%= link_to micropost.user.name, micropost.user %></span>
<span class="content">
<%= micropost.content %>
<%= image_tag micropost.picture.url if micropost.picture? %>
</span>
</li>
However the Micropost controller does not respond to the Ajax request but redirect to root_url, responding only to html (output from cloud9 server):
Started POST "/microposts" for 82.56.61.198 at 2017-07-14 09:44:55 +0000
Cannot render console from 82.56.61.198! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by MicropostsController#create as HTML
...
Started GET "/" for 82.56.61.198 at 2017-07-14 08:51:42 +0000
Cannot render console from 82.56.61.198! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by StaticPagesController#home as HTML
I do not understand why the create action of the Micropost controller does not respond to js format. I tried to clone partial _micropost.html.erb and use the instance variable #micropost instead of the variable micropost of the iteration, but it did not work. There are no errors in the server log.
Processing by MicropostsController#create as HTML
It is due to the limitation of AJAX. From the Reference
Ajax uses something called an xmlhttprequest to send your data.
Unfortunately, xmlhttprequests cannot post files
That said, you cannot post files via AJAX. You may need some help with Remotipart or Jquery-File-Upload
You only told the action to respond_to with format.js in your successful save path. You'll need to add a respond_to block with whatever you want to do for your js everywhere you render or redirect_to
Getting trouble with known at the title.
I have two forms in new.html.erb view. One is form_for, other one is form_tag, both as partials.
form_for is to save some data to models.
form_tag is to do little action with params. and give back the processed data to partilal(js). here I'm stuck. this not working.
form_tag is not working. after submitting, the action "urlchanger" don't reflect any data to partial "urlchanged". in My plan, this should get #url, but get errors (detail below).
This is the error respowned by submitting form_tag.
ActionController::RoutingError: No route matches [POST] "/notes/new"
..
Processing by Rambulance::ExceptionsApp#not_found as JS
Parameters: {"utf8"=>"✓", "url"=>"<iframe src=\"http://hogehoge.com/hoge" frameborder=0 width=510 height=400 scrolling=no></iframe>", "urlchanger"=>"変換"}
Rendered errors/not_found.json.jbuilder (0.2ms)
Completed 404 Not Found in 66ms (Views: 48.1ms | ActiveRecord: 0.0ms)
as the non partial. everything works fine.
but, I want them to work in single view.
notes
--new.html.erb
----_form.html.erb
----_urlchanger.html.erb
----_urlchanged.js
----_urlchanger.js.erb
!-------------notes/new.html.erb-------------!
<%= render 'form' %>
<%= render 'urlchanger' %>
!-------------notes/_urlchanger.html.erb-------------!
<%= bootstrap_form_tag(controller: "notes", action: "urlchanger", remote: true ) do |f| %>
<%= f.text_field :url, hide_label: true, :class => "form-control", placeholder: "ペーストエリア" %>
<%= f.submit "変換", data: { disable_with: '送信中'} %>
<div id="urlchanged" >
<%= render "urlchanged" %>
</div>
<% end %>
!-------------notes/_urlchanged.html.erb-------------!
<input type="text" class="form-control" value="<%= #url %>">
!-------------notes/_urlchanger.js.erb-------------!
$('#urlchanged').html('<%= j(render("urlchanged")) %>');
!-------------routes-------------!
resources :notes do
collection do
post :create
post :urlchanger
end
end
!-------------Notes controller-------------!
def urlchanger
url = params[:url]
if /(https?:\/\/\D*\w*)/ =~ url
#url = $&
end
end
Please help. Thank you.
What happens when you change your notes/_urlchanger.js.erb to notes/urlchanger.js.erb?
OR try this
def urlchanger
url = params[:url]
if /(https?:\/\/\D*\w*)/ =~ url
#url = $&
end
respond_to do |format|
# format.html { redirect_to(:back) } # no idea what you might want to do here
format.js { render partial: "notes/urlchanger" }
end
end
solved problem!!
I don't know why it works ('A')
But like the code blow works good.
---------------Note.controller----------------------
def urlchanger
url = params[:url]
if /(https?:\/\/\D*\w*)/ =~ url
#url = $&
end
respond_to do |format|
# format.html { redirect_to(:back) } # no idea what you might want to do here
format.js
end
end
------------------notes/_urlchanger.html.erb-------------------
<%= bootstrap_form_tag( url: notes_urlchanger_path, remote: true ) do |f| %>
I've a weird problem(I'm still learning rails) with rails and flash messages.
I have a link_to with method post in my rails view:
<%= link_to "<i class='fa fa-times'></i>".html_safe, email_post_path(#post.id), method: 'post' %>
and in my controller I do this:
def email_post
# do nothing
return redirect_to posts_path, alert: 'test flash'
end
The problem
is that works fine(so it redirect me correctly), but don't show the flash message(and the problem is not about the showing flash message, but that the flash[:alert] doesn't exists)
This is the way I show the flash messages:
<%= binding.pry %> #used for see if the flash is empty or not - and in this case is it!
<% flash.each do |type, message| %>
<div class="flash-<%= type %>">
<%= message %>
</div>
<% end %>
Why don't show the flash message in this case ?
Ok the problem seems to be
error: 'lol'
With:
alert: 'lol'
Works fine...why ?
I'm trying to display errors messages in my ajax form (the code is based on this question):
posts_controller.rb:
def create
#post = current_user.posts.build(params[:post])
if params[:commit] == "Publish"
#post.status = "Published"
elsif params[:commit] == "Save Draft"
#post.status = "Draft"
end
respond_to do |format|
format.html do
if #post.save && #post.status == "Published"
flash[:success] = "Post published"
redirect_to #post
elsif #post.save && #post.status == "Draft"
flash[:success] = "Post saved as draft"
render 'edit'
else
render 'new'
end
end
format.js do
#post.save
end
end
end
posts/create.js.erb:
<% if #post.errors.any? %>
alert('There are errors.');
<%= render :partial=>'js_errors', :locals=> { :target=> #post } %>
<% else %>
$('.busy').html('Saved.');
<% end %>
js_errors.js.erb:
<% target.errors.full_messages.each do |error| %>
$('.busy').append('<p><%= escape_javascript( error ) %></p>');
<% end %>
posts/new.html.erb:
<%= form_for(#post, remote: true, :html => { :multipart => true }) do |f| %>
<%= render 'fields', f: f %>
<div class="form-actions">
<%= f.submit "Publish", class: "publish btn btn-primary pull-left" %>
<%= f.submit "Save Draft", class: "save-draft btn btn-default pull-left" %>
<div class="busy pull-left">
</div>
</div>
<% end %>
But for some reason nothing displays (.busy always remain empty).
In the console I can see that js_errors.js.erb is being displayed:
Started POST "/posts" for 127.0.0.1 at 2013-01-04 18:02:18 +0800
Processing by PostsController#create as JS Parameters: {"utf8"=>"✓",
"authenticity_token"=>"Qfn6HsPPDxyB1t4bM/OQKPbJ/aoAMkp74y0Z6xkoXCY=",
"post"=>{"title"=>"", "content"=>"", "tag_list"=>""},
"_wysihtml5_mode"=>"1", "commit"=>"Save Draft"} User Load (0.7ms)
SELECT "users".* FROM "users" WHERE "users"."remember_token" =
'ljl0ZsuoiHg0Jilz8bgy-g' LIMIT 1 (0.2ms) begin transaction
(0.2ms) rollback transaction Rendered posts/_js_errors.js.erb
(3.8ms) Rendered posts/create.js.erb (7.5ms) Completed 200 OK in
25ms (Views: 11.2ms | ActiveRecord: 1.0ms | Solr: 0.0ms)
What could be the problem?
(I do see the validation messages if I remove remote:true from the form).
EDIT:
I noticed alert('There are errors.'); is not being triggered. Strange.
It looks like a naming problem. You're asking to render the partial js_errors, which would be called _js_errors.js.erb; but you say your file is actually called js_errors.js.erb (no leading underscore).
Try adding the underscore and see if that helps matters.
I have been facing a similar problem a few days ago. I used remote => true option in my form to use Ajax in my Rails 3 application. After that, I have been looking for solution for validating my form fields. After trying a good number of jQuery / Javascript approaches (none of them worked for me though) I came to know about a superb gem called client_side_validations. It is very easy to install by following the instructions on github link (https://github.com/bcardarella/client_side_validations). It works like charm for client side validation of form fields, an awesome gem indeed. Hope this helps with people who are tired of looking for a simple solution for client side validation of model fields after using Ajax in Rails 3 application.
I have a nav menu with 2 tabs/links in the show.html.erb file, in UsersController.rb, I would like to use ajax to render different partial for the tabs.
In the show.html.erb I have a div named profile-data where I want to show the content.
So I do something like this:
The link structure:
<li><%= link_to "College friends", college_friends_path, :remote => true %></li>
<li><%= link_to "Highschool friends", highschool_friends_path, :remote => true %></li>
I define the routes:
match "college_friends" => "users#college_friends", :as => "college_friends"
match "highschool_friends" => "users#highschool_friends, :as => "highschool_friends"
And I define in my UserController.rb the necessary methods:
class UsersController < ApplicationController
def show
#user = User.find(params[:id])
end
def college_friends
respond_to do |format|
format.js
end
end
def highschool_friends
respond_to do |format|
format.js
end
end
end
Last thing we have the JS files:
*college_friends.js.erb*
$('#profile-data').html("<%= escape_javascript(render(:partial => 'college_friends')) %>");
*highschool_friends.js.erb*
$('#profile-data').html("<%= escape_javascript(render(:partial => 'highschool_friends')) %>");
The partial code: _college_friends.html.erb
<% groups = #user.friends.group_by(&:college_name) %>
<% sorted_groups = groups.sort_by{|key, values| values.count}.reverse %>
<% sorted_groups.each do |collegename, friends| %>
<% next if collegename.blank? %>
<div class="contentbox">
<div class="box-header">
<h3><%= collegename %></h3>
<div class="meta-info">
<p><i class="icon-map-marker"></i> Malmö</p>
<p><i class="icon-user"></i><span class="count"> <%= friends.count %></span> vänner</p>
</div>
</div>
<ul class="friends-list">
<% friends.map do |friend| %>
<li><%= image_tag(friend.image) %>
<% end %>
</ul>
</div>
<% end %>
Nothing happens when I click the the links, and get this error in the console:
Started GET "/universitet_friends" for 127.0.0.1 at 2012-07-29 01:53:39 +0200
Processing by UsersController#universitet_friends as JS
Rendered users/_universitet_friends.html.erb (1.6ms)
Rendered users/universitet_friends.js.erb (3.1ms)
Completed 500 Internal Server Error in 7ms
ActionView::Template::Error (undefined method `friends' for nil:NilClass):
1: <% groups = #user.friends.group_by(&:college_name) %>
2: <% sorted_groups = groups.sort_by{|key, values| values.count}.reverse %>
3: <% sorted_groups.each do |collegename, friends| %>
4: <% next if collegename.blank? %>
app/views/users/_universitet_friends.html.erb:1:in `_app_views_users__universitet_friends_html_erb___1983680250475155079_70236040373720'
app/views/users/universitet_friends.js.erb:1:in `_app_views_users_universitet_friends_js_erb__1317362850668628869_70236044930260'
app/controllers/users_controller.rb:19:in `universitet_friends
Any help would be appreciated.
ActionView::Template::Error (undefined method `friends' for
nil:NilClass):
This is telling you that your #user variable is nil. This happened because when you went back to your controller for the AJAX request, you never actually set the #user variable. It does not persist between requests. You need to pass that variable during the ajax request. One way to do it is to add a user_id param to the ajax URL.
May be you can do something like this too
<%=link_to "Highschool friends", college_friends_path(:user_id => #user.id), :remote => true %>
The best way to do however would be to pass the user_id param to ajax url..you can fire the ajax request on link "on-click" event.