Rails: Flash Messages not appearing anywhere - ruby-on-rails

So let's say I have code like this:
class PostsController < InheritedResources::Base
# Add before_filter here and devise should handle the redirection if the user is not signed in.
before_filter :authenticate_user!, only: [:vote_up]
def vote_up
begin
current_user.vote_for(#post = Post.find(params[:id]))
redirect_to [#post]
flash[:success] = "You have voted successfully"
rescue ActiveRecord::RecordInvalid
redirect_to [#post]
flash[:error] = "You have already voted"
end
end
end
Neither of the messages "You have voted successfully" or "You have already voted" are being shown.
In my view I have:
enter code here
<p id="notice"><%= notice %></p>
<%= #post.embed .html_safe %>
<header>
<h7><%= #post.name %></h7>
</header>
<h8><%= #post.title %></h8>
<article>
<%= #post.content .html_safe %>
<p>
<%= link_to 'Back', posts_path %> |
<%= link_to('Vote for this song!', vote_up_post_path(#post), :method => :post) %></p>
<p><id="notice"><%= notice %></p>
No dice. I'm still not getting flash messages anywhere. Any idea what I'm doing wrong?

You have used
flash[:success] = "You have voted successfully"
in your controller and you have called
<%= notice %>
in your views. You have to change either in your controller or in your views.
You can add
format.html { redirect_to #post, notice: 'You have voted successfully.' }
in your controller and you will get the message that you require.

You should set the flash before redirect_to
And in your view
<p>
<%= flash[:success] unless flash[:success].blank? %>
<%= flash[:error] unless flash[:error].blank? %>
</p>
You can check this link as well

The best way to do it
<% if flash[:notice] %>
<div class="notice"><%= flash[:notice] %></div>
<% end %>

Your code is like: <p><id="notice"><%= notice %></p>
You need <p id="notice"><%= notice %></p>

Related

Flash messages only show after redirecting twice

flash[:errors] does not show after redirect_to in create method. But if I send another invalid form it shows up on the second and all following redirects. The same goes for flash[:success] when there are no errors.
I've tried using flash.keep in both this and the route I am redirecting to, and the views work since the messages do appear after multiple redirects. I'm wondering if it is because the redirects are to routes that render too?
In Controller:
def create
user = User.create(user_params)
if user.errors.any?
flash[:errors] = user.errors.full_messages
redirect_back(fallback_location: root_path)
else
flash[:success] = "USER SUCCESSFULLY CREATED"
redirect_to root_path
end
end
In Views:
<% if flash[:errors] %>
<% flash[:errors].each do |error| %>
<p style="color:red;"><%= error %></p>
<% end %>
<% end %>
AND:
<% if flash[:success] %>
<p style="color: red;"><%= flash[:success] %></p>
<% end %>
No flash messages are shown after the first redirect. After or more redirects, the flash messages are shown

Ruby on Rails modal form submitting to wrong DB

I have a modal on a searches/show page:
<button name="button" type="button">
<a class="nav-link" data-toggle="modal" data-target="#emailFriendModal" href="">Email Results to Friend</span></a>
</button>
On click, the modal correctly brings up this partial (most of the code redacted for brevity):
<div class="modal fade" id="emailFriendModal">
...
<div class="mx-auto text-left column">
<%=form_with id: :friend_email_form, url: friend_emails_create_path do |f|%>
...
<%= recaptcha_tags %>
<div class="actions">
<%= f.submit "Send Email", class: 'btn btn-primary', "onclick":"submit_form();", "data-dismiss":"modal"%>
</div>
<script>
function submit_form() {
document.getElementById('friend_email_form').submit();
}
</script>
<%end%>
</div>
But on submit, the object is not sent to the friend_emails Controller:
class FriendEmailsController < ApplicationController
def new
#friend_email = FriendEmail.new
end
def create
#friend_email = FriendEmail.new(message: params[:message], email: params[:email], email2: params[:email2], path: params[:path])
if #friend_email.save
redirect_back fallback_location: root_path, notice: "Your email has been sent"
else
redirect_back fallback_location: root_path, notice: "Sorry, something went wrong, please try again"
end
end
def friend_email_params
params.require(:friend_email).permit(:message,:email,:email2,:path)
end
end
When the "Email a Friend" button is clicked, the correct partial pops up, but when the form is submitted, a Tour object is created (not a Friend_email object!!). The tour message is displayed, a tour email is sent. On submit the the info is completely bypassing the Friend_emails controller and going straight to the Tour controller.
Routes:
post "friend_emails/create"
post "tours/create"
Rake Routes:
friend_emails_create POST /friend_emails/create(.:format) friend_emails#create
tours_create POST /tours/create(.:format) tours#create
Tours Controller in case its helpful:
class ToursController < ApplicationController
def index
#tours = Tour.all
end
def new
#tour = Tour.new
end
def create
#tour = Tour.new(day: params[:day], time: params[:time], user_id: params[:user_id], listing_id: params[:listing_id], school_id: params[:school_id],
email: params[:email])
if #tour.save
redirect_back fallback_location: root_url, notice: "Your tour request has been sent; we will be in touch soon with confirmation."
else
redirect_back fallback_location: root_url, notice: "#{#tour.errors.full_messages}"
end
end
def destroy
#tour = Tour.find(params[:id])
#tour.destroy
redirect_back fallback_location: root_url, notice: "Your Tour has been Cancelled"
end
def tour_params
params.require(:tour).permit(:tour_req, :user_id, :listing_id, :school_id, :email, :day, :time)
end
end
And Finally, this is an excerpt from the Application Layout which holds the partials.
<%= yield %>
<% unless user_signed_in? %>
<%= render partial: 'devise/registrations/new' %>
<%= render partial: 'devise/sessions/new' %>
<% end %>
<%= render partial: 'friend_emails/new'%>
<%= render partial: 'tours/new'%>
I figured out the problem. I had two modals in the application layout and the code referenced the same javacript submit() function. The fix was to change the name of the submit() function like this:
<div class="actions">
<%= f.submit "Send Email", class: 'btn btn-primary', "onclick":"submit_form2();", "data-dismiss":"modal"%>
</div>
<script>
function submit_form2() {
document.getElementById('friend_email_form').submit();
}
</script>
Now we have two javascript functions, submit_form() and submit_form2() and everything works as it should.

No template found for UsersController#create, rendering head :no_content

OK, previously I had a problem with a no template error from users#create, now it complete 200 OK however does not redirect at all. Below is my edited users_controller.rb
I have a Signup, Login, Logout rails application with users as a resource. I am trying to save the first user in the database so I can then login but this error is server output when I try to "users#new" and "users#create" the full error is below, then my users_controller.rb and views/users -> new.html.erb
No template found for UsersController#create, rendering head :no_content
Completed 204 No Content in 35ms (ActiveRecord: 0.5ms)
users_controller.rb
def new
#user = User.new
end
def create
#user = User.new(user_params)
if (#user = User.find_by_email(params[:email]))
flash[:success] = "User already exists."
if #user.save
session[:user_id] = user.id
flash[:success] = "New User created."
redirect_to '/layouts/application'
else
render 'new'
end
end
end
new.html.erb
<h1>Sign Up</h1>
<%= form_with(model: #user) do |f| %>
<p> Username:</br> <%= f.text_field :username %> </p>
<p> Email:</br> <%= f.text_field :email %> </p>
<p> Password:</br> <%= f.password_field :password%></p>
<%= f.submit "Signup" %>
<% end %>
<% if #user.errors.any? %>
<ul class="Signup_Errors">
<% for message_error in #user.errors.full_messages %>
<li>* <%= message_error %></li>
<% end %>
</ul>
<% end %>
</div>
Do I have to have another html.erb file? And how can I tell what that has to be? Sorry for the obvious question, newb here.
As per your code if the User is not present it will not enter in the if block. Rails end up trying to find create.html as the current action is create.
To avoid this you must redirect it somewhere or render a template which you have done in the next if and else but it's not executing.
The condition is not letting it redirect to anywhere. Try moving the if block out like this.
def create
#user = User.new(user_params)
if User.exists?(email: params[:email]) # I think this should be `user_params[:email]` instead of `params[:email]`
flash[:error] = "User already exists."
redirect_to 'whereever/you/want/to/redirect' and return
end
if #user.save
session[:user_id] = user.id
flash[:success] = "New User created."
redirect_to '/layouts/application'
else
render 'new'
end
end

Flash message not displayed with redirect_to named_route_url in rails 4

In one controller I have
flash.keep[:notice]= "Your password has been updated successfully."
redirect_to organisation_show_url
In application layouts file I have
<% if flash[:notice] %><div class="notice"><%= flash[:notice] %></div><% end %>
But no flash message is displayed on the organisation_show page, what did I do wrong
In your controller
redirect_to organisation_show_url, :notice => "Your password has been updated successfully."
In application layout
<% if notice %>
<%= notice %>
<% end %>

how to catch mongoid validation erros from another controller?

I have 2 controllers: DocumentsController and DashboardController
After the user login successful, he is redirected to dashboard_path, which has a form to create a 'fast document' like this
<%= form_for #document, :html => {:class => 'well'} do |f| %>
<% if #document.errors.any? %>
<div id="alert alert-block">
<div class="alert alert-error">
<h2>Couldn't create your doc. :(</h2>
<ul>
<% #document.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
</div>
<% end %>
<label>A lot of fields</label>
<%= f.text_field :fields %>
<div class="form-actions">
<%= f.submit 'Create document', :class => 'btn btn-large' %>
</div>
<% end %>
but when an exception happen (like the user forgot to fill a field), I would like to show these exceptions, not just an alert saying 'Error'...actually, I didn't found a way to do this
here's my DashboarController
class DashboardController < ApplicationController
before_filter :authenticate
def index
#document = Document.new
end
end
and my DocumentsController
class DocumentsController < ApplicationController
respond_to :json, :html
def show
end
def create
#document = Document.new(params[:document])
#document.user = current_user
if #document.save
redirect_to dashboard_path, notice: 'Created!'
else
flash[:error] = 'Error!'
redirect_to dashboard_path
end
end
end
any help is appreciated :)
You are correctly redirecting on success; on failure, though, should not redirect; you need to render the template where the form was filled.
if #document.save
redirect_to dashboard_path, notice: 'Created!'
else
render 'dashboard/index'
end
You'll have to make sure that any variables needed by the index template are available in the create action of the documents_controller (you're just rendering the index template; you're not running the code from the dashboard controller's index action). Here's a excerpt from the relevant Rails Guide to clarify:
Using render with :action is a frequent source of confusion for Rails newcomers. The specified action is used to determine which view to render, but Rails does not run any of the code for that action in the controller. Any instance variables that you require in the view must be set up in the current action before calling render.
More at http://guides.rubyonrails.org/layouts_and_rendering.html#using-render

Resources