Rails4 Form with remote - handling error message - ruby-on-rails

I have a simple remote form like this:
= form_for :question, :url => question_path, :remote => true, :html =>{:class => 'question-form'} do |form|
and in my controller I check if in the form the EULA is accepted:
def create
if (params[:question][:eula] != 1)
puts "ERROR!"
respond_to do |format|
return format.json {render :json => {:error_message => "FOOOO", :success => false } }
end
end
#question = Question.new(question_params)
respond_to do |format|
if #question.save
format.html { redirect_to #question, notice: 'question was successfully created.' }
format.json { render :show, status: :created, location: #question }
else
format.html { render :new }
format.json { render json: #question.errors, status: :unprocessable_entity }
end
end
end
How can I access :error_message or :success in my create.js.erb file?

You can do Ajax request
add id to form :id => "question-form"
= form_for :question, :url => question_path, :remote => true,
:html =>{:class => 'question-form', :id => "question-form"} do |form|
and anywhere in javascript file
$("#question-form").on("submit", function(e){
e.preventDefault();
var form = $(this);
var request = $.ajax({
method: "POST",
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
url: "/questions",
dataType: "json",
data: form.serialize()
})
request.done(function(res){
console.log(res.success);
})
request.catch(function(jqXHR){
console.log(jqXHR.responseJSON)
})
})

Related

Not Update Dynamic Select rails

I have a problem, i implement dynamic select, but does not update ciudades.
someone has occupied this code?
my code.
autos.coffee:
$ ->
$(document).on 'change', '#regiones_select', (evt) ->
$.ajax 'update_ciudades',
type: 'GET'
dataType: 'script'
data: {
region_id: $("#regiones_select option:selected").val()
}
error: (jqXHR, textStatus, errorThrown) ->
console.log("AJAX Error: #{textStatus}")
success: (data, textStatus, jqXHR) ->
console.log("Dynamic region select OK!")
Autos Controller:
class AutosController < ApplicationController
before_action :set_auto, only: [:show, :edit, :update, :destroy]
def index
#autos = Auto.all
end
def show
end
def new
#regiones = Region.all
#ciudades = Ciudad.where("region_id = ?", Region.first.id)
#auto = Auto.new
end
def edit
end
def create
#auto = Auto.new(auto_params)
respond_to do |format|
if #auto.save
format.html { redirect_to #auto, notice: 'Auto was successfully created.' }
format.json { render :show, status: :created, location: #auto }
else
format.html { render :new }
format.json { render json: #auto.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #auto.update(auto_params)
format.html { redirect_to #auto, notice: 'Auto was successfully updated.' }
format.json { render :show, status: :ok, location: #auto }
else
format.html { render :edit }
format.json { render json: #auto.errors, status: :unprocessable_entity }
end
end
end
def destroy
#auto.destroy
respond_to do |format|
format.html { redirect_to autos_url, notice: 'Auto was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_auto
#auto = Auto.find(params[:id])
end
def auto_params
params.require(:auto).permit(:region_id, :ciudad_id,)
end
end
_form.html.erb:
<%= form_for #auto, url: {action: "create"}, html: {method: "post"} do |f| %>
<%= f.select :region_id, options_for_select(#regiones.collect { |region|
[region.region.titleize, region.id] }, 1), {}, { id: 'regiones_select' } %>
<%= f.select :ciudad_id, options_for_select(#ciudades.collect { |ciudad|
[ciudad.ciudad.titleize, ciudad.id] }, 0), {}, { id: 'ciudades_select' } %>
<%= f.submit "Go!" %>
<% end %>
new.html.erb:
<h1>New Auto</h1>
<%= render 'form' %>
<%= link_to 'Back', autos_path %>
the code doest work...
regards

render error messages with js form rails

I changed my form to remote, and while the form now works, the error messages are no longer displaying if there's an error.
<%= render 'shared/error_messages' %>
is there a good wear to get the messages to show again?
below is my controller...
thank you.
respond_to do |format|
if #post.save
format.js { render :js => "window.location = '#{edit_post_path #post}'" }
format.html { redirect_to [:edit, #post] }
else
format.js { render :js => #post.errors }
format.html { redirect_to '/', :error => "Could not save comment" }
end
end
respond_to do |format|
if #post.save
format.js { render :js => "window.location = '#{edit_post_path #post}'" }
format.html { redirect_to [:edit, #post] }
else
format.js { }
format.html { redirect_to '/', :error => "Could not save comment" }
end
end
# update.js.erb
$(document).find("form").prepend('<%= escape_javascript(render("shared/error_messages", :formats => [:html])) %>');

Why do I get No Route Error in Rails 3 even though I have defined a route?

This is the error:
ActionView::Template::Error (No route matches {:action=>"send_to_client", :controller=>"stages"}):
app/views/stages/_show.html.erb:13:in `_app_views_stages__show_html_erb__3606907191157577988_2203521120_617355097038007272'
app/controllers/stages_controller.rb:78:in `block (2 levels) in create'
app/controllers/stages_controller.rb:75:in `create'
This is line 13 in the _show.html.erb:
<%= link_to "<span class='icon send-to-client-icon' title='Send to Client'> </span>".html_safe, send_to_client_stage_path, :id => stage.id, :confirm => "This will send #{stage.name.capitalize} to #{stage.client.email}. Are you sure you are ready?" %>
This is my stages controller, create action:
def create
#stage = current_user.stages.create(params[:stage])
client = #stage.client
unless #stage.new_record?
respond_with(#stage, :status => :created, :location => #stage) do |format|
flash.now[:notice] = 'Stage was successfully created.'
format.html { redirect_to(#stage) }
format.js { render :partial => "stages/show", :locals => {:stage => #stage, :client => client}, :layout => false, :status => :created }
end
else
respond_with(#stage.errors, :status => :unprocessable_entity) do |format|
format.js { render :json => #stage.errors, :layout => false, :status => :unprocessable_entity }
format.html { render :action => "new" }
end
end
end
Stages Controller, send_to_client action:
def send_to_client
stage = Stage.find(params[:id])
ClientMailer.send_stage(stage).deliver
if ClientMailer.send_stage(stage).deliver
flash[:notice] = "Successfully sent to client."
redirect_to("/")
else
flash[:notice] = "There were problems, please try re-sending."
redirect_to("/")
end
end
You are missing the ID and need to pass the stage instance it in your send_to_client_stage_path call.
send_to_client_stage_path(stage)
instead of:
send_to_client_stage_path

Rails: routing update error

I am getting a routing error: No route matches "/deccom_tasks/update/1" with {:method=>:put}
I'm not sure why I am getting a routing error for a route that usually works.
Route:
map.resources :decom_tasks, :collection => {:sort => :post, :deactivate_task => :get, :reactivate_task => :get}
Controller:
def update
#task = Task.find(params[:id])
respond_to do |format|
if #task.update_attributes(params[:task])
format.html { redirect_to(#task, :notice => 'Task was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => #task.errors, :status => :unprocessable_entity }
end
end
end
Mark Thomas was right, syntax error

ajax request with form_remote_tag doesn't work

So I'm using a form_remote_tag to attempt an ajax form submission, like so:
<% form_remote_tag :update=> 'test', :url=> {:action=>'test_action'} do -%>
It renders with no apparent problem:
<form action="/pages/test_action" method="post" onsubmit="new Ajax.Updater('test', '/pages/test_action', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;">
The test_action action:
def test_action
if request.xhr?
render :text => 'some text'
else
puts 'nope'
end
end
When I submit the form(via the submit button, nothing weird like the jquery submit() event), no ajax request is made. The xhr check returns false. Help please??
In controller you should respond to specified format, js in your case. For example:
def create
#item = Item.new(params[:item])
respond_to do |format|
if #item.save
flash[:notice] = 'Item was successfully created.'
format.js
format.html { redirect_to(#item) }
format.xml { render :xml => #item, :status => :created, :location => #item }
else
format.html { render :action => "new" }
format.xml { render :xml => #item.errors, :status => :unprocessable_entity }
end
end
end
The best practice for now is to use unobtrusive javascript (UJS). There is no form_remote_tag in rails 3. UJS can be used with rails 2.3 as well.

Resources