The problem in brief: I'm working on a rails 4 app (4.1.8) and I'm trying to get flash[:notice] and flash[:alert] to show up under a form.
Two controllers: landingpage_controller and contacts_controller. The landingpage_controller serves a static landingpage through its show action and the contacts_controller has new and create actions, to store the contacts in a db table.
On the static landingpage, a modal with id="contact-modal" contains a partial with a simple_form_for #contact (see below). Upon submittal of the form, a db-entry is not created if the fields are not all filled out and a db-entry is created if the fields are filled out. However, no flash messages are displayed.
Wanted output:
Ideally the partial would re-load without leaving/closing the modal, with either: a success message and an empty form or a alert message and the form as it was upon submittal. How do I do this?
The controller: app/controllers/contacts_controller.rb
class ContactsController < ApplicationController
def new
#contact = Contact.new
render layout: "contact"
end
def create
#contact = Contact.new
respond_to do |format|
if #contact.save
flash[:notice] = "Success"
format.js
else
flash[:alert] = "Error"
format.js
end
end
end
private
def contact_params
params.require(:contact).permit(:email, :structure, :message_content)
end
end
The form: app/views/contacts/_new.html.haml
= simple_form_for #contact, html: { id: "contact-form"} do |c|
= c.input :email
= c.input :structure
= c.input :message_content
= c.button :submit
.messages-container
= if flash[:notice]
%p
= flash[:notice]
= if flash[:alert]
%p
= flash[:alert]
Routes:
resources :contacts, only: [:new, :create]
I'm aware that a partial reload probably involves AJAX. I've read several StackOverflow questions on this but have not been able to figure it out. See here, here and these two blog-posts: jetthoughts, ericlondon.
Your help is very much appreciated
There are several problems in your code:
views, that start with underscore are called partials and are not full actions, but just parts of reusable view code (you don't redirect to them, instead you use render since you usually don't want a full page reload.
1.1 Rename your _new.html.haml to _form.html.haml
2.1 Create a new view new.html.erb(I guess you have that already, otherwise your new action might not work properly) with content = render 'form'
From what I understand you don't want the modal to close, just to render a form after successful submission or if there is an error.
In that case:
1.create a create.js.erb file in your views/contacts folder
create.js.erb
$("#your_modal_id").html("<%= j( render 'form') %>")
2. change your create action
def create
#contact = Contact.new(contact_params)
respond_to do |format|
if #contact.save
flash[:notice] = "Success"
format.js
else
flash[:alert] = "Error"
format.js
end
end
end
to your form add remote: true
WARNING: This will leave your form filled in even if it is successful.
More about this topic see:
http://guides.rubyonrails.org/v4.1.8/working_with_javascript_in_rails.html#form-for
Hope it helps, and I hope I didn't forget anything
Related
Let's say I create a scaffold:
rails g scaffold Cat name:string age:integer
and I add a presence validation on the Cat model's age attribute:
validates :age, presence: true
When I attempt to create a cat via the form, and put in the cat's name but purposely leave out the cat's age the controller bounces me back to the form but that cat's name is still present in the name field!
How is this happening?
I would have thought the
#cat = Cat.new
would replace all of the invalid cat's attributes. Maybe if it were #cat ||= Cat.new I could understand that more.
Also, how can I make this behaviour happen in a more complex rails app? I have a simple forum where topics has_many replies. I create my new replies via a form in my topic show view:
topic#show:
#reply = Reply.new
topic/show.html.erb:
<%= form_for [#toplic, #reply] do |f| %>
<%= f.text_field :name placeholder: 'Create a new name...' %><br>
<%= f.text_area :description, placeholder: 'Create a new description...', rows: 5 %><br>
<%= f.submit 'Create Discussion' %>
<% end %>
While everything works perfectly, when I purposely leave out a reply's name, though I am redirected back to the form and an error flash shows, my form is completely empty. All of the attributes have vanished? Why is this?
The key to understanding how this works is to realize that in the case of a form failure, the controller action is not rerun, but rather the template is rendered using the existing state from the action.
In a typical Rails scaffold, your create action will look like this
def create
#cat = Cat.new(cat_params) # instance variable is initialized with the form values
if #cat.save
redirect_to #cat, notice: 'Success!'
else
# in the case of form failure, we will re-render the 'new' template
# this will NOT rerun the entire 'new' action, thus the #cat variable
# will still maintain the values from the form that we gave it above
render 'new'
# note the difference if we had instead done a redirect_to; this would
# cause the CatsController#new action to be re-run which would reinitialize
# the #cat variable according to the code within the 'new' action
# redirect_to new_cat_url
end
end
For your more complex example, you'll want to follow the same procedure, making sure you just re-render the form and don't redirect to another action (which will cause the state to be lost).
# TopicsController
def show
#topic = Topic.find(params[:id])
#reply = Reply.new
end
# RepliesController
def create
#reply = Reply.new(reply_params) # init the var with the form values
if #reply.save
redirect_to #topic, notice: 'Success!'
else
# this is the key - we need to re-render the template of the previous action
# in this case, it would be the TopicsController#show template
render 'topics/show'
# Remember - if we instead do a redirect_to #topic, then we will lose the form
# values which are currently set in the #reply variable.
end
end
In short, make sure you recognize when you are redirecting to a new action versus just re-rendering a template.
One important GOTCHA to be aware of when re-rendering a template is that you must make sure that all the instance variables which exist for the controller action are available when you render the template.
For example,
# TopicsController
def show
#topic = Topic.find(params[:id])
#reply = Reply.new
#foo = Foo.new
end
# RepliesController
before_action :set_topic
def create
#reply = Reply.new(reply_params)
if #reply.save
# ...
else
# we need to remember to set up a #foo variable here otherwise it will be undefined
# when used within the 'show' template
#foo = Foo.new
render 'topics/show'
end
protected
def set_topic
#topic = Topic.find(params[:topic_id])
end
OK, so, you go go /cat/new. Rails' route for this URL runs the method CatsController#new, which renders the new.html.erb template. You put in your data, then hit submit. The action for this form is to POST to /cats, which runs the CatsController#create method. This method does this following:
#cat = Cat.new(cat_params)
It then tries to save the Cat. If it succeeds, it redirects you to the Cat's URL. If not, it re-renders the new.html.erb template. That's where the name comes from — the CatsController#update method creates its Cat from the values you put into the original form.
For a typical scaffold create action:
# POST /products
# POST /products.json
def create
#product = Product.new(params[:product])
respond_to do |format|
if #product.save
format.html { redirect_to #product, notice: 'Product was successfully created.' }
format.json { render json: #product, status: :created, location: #product }
else
format.html { render action: "new" } #will re-submit
format.json { render json: #product.errors, status: :unprocessable_entity }
end
end
end
The magic happens in the render method! which will submit the previous POST request (won't go back to the new action while a redirect will do), this way the submited values are still there. (check this SO question for more details)
That's said, this behavior relies on following the convention, however sometimes you need to give it a hand specially with some inputs (e.g selects, checkboxes, radio) might require extra setup using selected or value options
In ruby on rails project, when I create a reporter successfully, page is redirect to another action from another controller; and when the page is redirect, the page is reloaded. In this project, I have 2 controller:
reporters_controller.rb:
class ReportersController < ApplicationController
layout "reporter"
def new
#reporter = Reporter.new
#gomrokaddresses = Gomrokaddress.find(:all)
end
def create
#reporter = Reporter.new(reporter_params)
if #reporter.save
#redirect_to new_reporter_path
redirect_to new_problem_path(:id => #reporter.id)
else
#existreporter = Reporter.find_by(params[:rep_user_name])
redirect_to new_problem_path(:id => #existreporter.id)
end
end
problems_controller.rb
def new
#reporter = Reporter.find(params[:id])
#problem = #reporter.problems.build
end
def create
#reporter = Reporter.find(params[:id])
#problem = #reporter.problems.build(problem_params)
if #problem.save
redirect_to new_problem_path(:id => #reporter.id)
else
redirect_to new_problem_path(:id => #reporter.id)
end
end
reporter.rb
class Reporter < ActiveRecord::Base
has_many :problems
end
problem.rb
class Problem < ActiveRecord::Base
belongs_to :reporter
end
I create reporter and problem with form_for in view. When I complete form_for in new.html.erb (for reporter) and submit, create action (that exist in reporter_controller) is called, and then if information are true, page is redirect to /problems/new. Because of this redirect_to, the page is reload; I don't want reload the page, just when I create the reporter, the form_for of reporter replace with the form_for of problem. How can I do this?
Try this in your controller
redirect_to new_problem_path(:id => #reporter.id), format: 'js'
Hope this helps!
A controller action renders the corresponding view template by default. Here, the action "problems#new" automatically renders "views/problems/new.html.erb".
In your code, you've redirected to the URL represented by new_problem_path, and a GET request to that URL is routed to the "problems#new" action. Thus, the action is invoked and its template is loaded.
However, there are ways to override this default behavior if you want to call the action without loading the view template.
Also, redirect_to is different from AJAX. For AJAX, you'd use something like
def create
...
respond_to do |format|
if #reporter.save
format.html { redirect_to ... }
format.js
else
format.html { render action: ... }
format.js
end
end
end
and then add the option :remote => true to form_for in the form that you use to create the new reporter.
But I'm not sure if this would accomplish what you're trying to do. Could you please explain your question further?
In my Ruby on Rails application, each group has_many :expenses. I have nested my routes, so expenses are entered only as child entities of their parent groups. Here's an excerpt from routes.rb.
resources :groups do
resources :expenses
end
I cannot figure out how to render the 'new' action in the case of an expense not saving when it is submitted through /groups/:group_id/expenses/new. In my expenses_controller.rb, here is how the create action is defined:
def create
#expense = Expense.new(params[:expense])
#expense.group_id = params[:group_id]
if #expense.save
redirect_to group_expense_path(#expense.group.id, #expense.id)
else
render 'new'
end
end
Everything works fine if I satisty expense validation and #expense.save winds up working. However, when it fails and the code tries to render 'new' I get:
undefined method `expenses_path' for #<#<Class:0x007fd408b1fd58>:0x007fd408f21ca8>
So, I am assuming I have something about my nested routing wrong. How do I return the user to the new form but still display to him/her through the flash[] params the errors with the data they originally attempted to submit?
The problem is that #group is not initialized
So in your controller just do
#expense = Expense.new(params[:expense])
#group = Group.find(params[:group_id])
#expense.group_id = #group.id
Looks like you need to explicitly specify the url for form_for in your view.
Something like…
<%= form_for #expense, :url => group_expenses_path(#group.id) do |f| %>
...
<% end %>
In your <%= form_for %> you have used #group for url, because expenses belongs_to groups. But inside your create action in the controller you have not defined what is #group, so first you should define it as:
#expense = Expense.new(params[:expense])
#group = Group.find(params[:group_id])
#expense.group_id = #group.id
Also I would suggest to use respond_to in your controller:
respond_to do |format|
if #expense.save
format.html { redirect_to group_expense_path(#group.id, #expense.id), :notice => "Any msg you want" }
else
format.html { render :action => "new" }
end
end
All of these are in your create action inside the controller.
Also for different rendering methods look up: http://guides.rubyonrails.org/layouts_and_rendering.html
Hope this helps!
I have built a dashboard of sorts with multiple forms from different models in the same view. My goal is to have all of the error messages from each form render on the dashboard. The dashboard is part of the PagesController and the forms belong to other controllers.
All of the forms currently work great. However, when errors occur they render in other views not the dashboard. When I attempt to "render" the errors on the dashboard page I get errors that the other form's models are missing.
Example of "render" that renders outside of the dashboard view.
class NotesController < ApplicationController
def create
#note = Note.new(params[:note])
if #note.save
flash[:notice] = "Note Created!"
redirect_to dashboard_path
else
flash[:alert] = "Note failed"
render :action => "new"
end
end
end
The example I would like to work, which renders the errors inside the dashboard view.
class NotesController < ApplicationController
def create
#note = Note.new(params[:note])
if #note.save
flash[:notice] = "Note Created!"
redirect_to dashboard_path
else
flash[:alert] = "Note failed"
render 'pages/home'
end
end
end
To reiterate, I am trying to make it so all errors will show up on the dashboard page with out breaking the site. Let me know if you would like more information.
You can accomplished this by just setting errors to an instance variable that all the forms use:
class NotesController < ApplicationController
def create
#note = Note.new(params[:note])
if #note.save
flash[:notice] = "Note Created!"
redirect_to dashboard_path
else
#errors = #note.errors
load_home
render 'pages/home'
end
end
private
def load_home
#instances = Model.all
#instance_1 = Model.find(1)
end
end
All your controllers would set #errors = #model.errors then in your view you just have something like this instead of relying on f.error_messages or whatever you have in your form:
(in haml)
- unless #errors.nil?
#errorExplanation
%h2 Please correct these errors
%ul
- for e in #errors
%li= e[1]
I have a Post that has_many :comments and a Comment that belongs_to :post.
On /posts/:id (the post show method) I render a form where users can leave comments.
It all works, validations, tests and posting is just fine. Only thing missing is how to re-render the POSTed data on validation errors.
The (simplified) code for this is:
#app/controllers/posts_controller.rb
class PostsController < ApplicationController
def index
#posts = Post.all_published(params[:page])
#title = "Blog"
end
def show
#post = Post.where({:published => true}).find(params[:id])
#comment = Comment.new(:post => #post)
#title = #post.title
end
end
#app/controllers/comments_controller.rb
class CommentsController < ApplicationController
def create
#comment = Comment.new(params[:comment])
puts #comment
if #comment.save
flash[:notice] = 'Comment was successfully created.'
redirect_to(#comment.post)
else
flash[:notice] = "Error creating comment: #{#comment.errors}"
redirect_to(#comment.post)
end
end
end
#app/views/posts/show.haml
.html renders Post contents.
- form_for #comment do |f|
= f.hidden_field :post_id
= f.text_area :body
= f.text_field :name
.some more fields.
I expect the solution to be either in some magical declaration in the comments_controller.rb, part
else
flash[:notice] = "Error creating comment: #{#comment.errors}"
redirect_to(#comment.post)
end
Or in the PostsController.show where I prepare the #comment. Should I set that #comment conditional and fill it with some magic variable on errors?
Or did I make some entirely different mistake?
If you redirect, that data is usually lost, thats why in most cases in create create actions you would have noticed that in the false scenario, render not redirect_to.
So instead you could just try,
flash[:notice] = ""Error creating comment: #{#comment.errors}"
render :template => "posts/show"
#post = #comment.post
# you may need to pre-populate the instance variables used inside PostsController#show