request not entering into the controller action - ruby-on-rails

i have been trying this from long time but not getting what is the mistake that i am doing,
here is my controller
class UsersController < ApplicationController
puts "before"
def create
puts "hiiiiiiiiiiiiiiiiii"
puts params
User.create(:birthday=> params["dateOfBirth"],:email=> params["emailId"])
end
puts "after"
end
and here is my routes
post '/sign_up', :to => "users#create"
this is giving me a 200 OK response code but not actually entering into the method "create" and storing the values in databse
it is priting "before" and "after" but not "hiiiiii"
looks like i am doing some silly mistake but need help to get it done
thanks.!
This is how i am doing query from client side.
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
}
});
var registration = function(){
var user = {
firstname : $("#firstname").val(),
lastname : $("#lastname").val(),
emailId : $("#email").val(),
password : $("#psw").val(),
dateOfBirth : $("#birthday").val() };
$.post("/sign_up", user, function(data){
console.log(data);
},'json');
};

For really good debug pupposes use gem rails-pry. Add gem 'pry-rails' to your gemfile, run 'bundle install'. Now you can add 'binding.pry' to any place of your code, and when your app reach this line you will have a full access to this code from console. It's better than use 'puts'.
For your In you case it would be:
class UsersController < ApplicationController
puts "before"
def create
binding.pry
User.create(:birthday=> params["dateOfBirth"],:email=> params["emailId"])
end
puts "after"
end
Run application, open your browser and go to url. Than open console and you will be 'inside' create action
UPDATE
Look at my example, I've created it and all works good
Model: User.rb
class User < ActiveRecord::Base
attr_accessible :city, :email, :gender, :name
end
Controller: UsersController.rb
def create
binding.pry
#user = User.new(params[:user])
session[:user] = #user
respond_to do |format|
if #user.save
format.html { redirect_to users_path, notice: 'User was successfully created.' }
format.json { render json: #user, status: :created, location: #user }
else
format.html { render action: "new" }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
users.js:
$(function() {
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
}
});
var registration = function(){
alert('a');
var user = {
name : $("#name").val(),
city : $("#city").val(),
gender : $("#gender").val()
};
$.post("/sign_up", user, function(data){
console.log(data);
},'json');
}
$('#but').click(registration);
});
new.html.erb:
<form>
<input id="name">
<input id="city">
</form>
<button id="but">create</but>
routes.rb:
resources :users
post '/sign_up', :to => "users#create"
root :to => 'users#new'
I run application, fill form, open console -> I'm in create action

Related

How to update Item with one click?

I want to update Item that are stored in my DB with one click.
For example i have model called Car. It has attribute called "active" which is Boolean so could be 0 or 1 in DB. I want that users have a possibility to change this this attribute with one click for example from index page of their cars. I know that it could be done if i would make this button like the whole form. But i think it is not the best solution and not right. Could i make it in any another way, maybe create special link_to or something like this?
As i understand it should send request to CarsController into update method, but how to do this without form?
You simply need to use link_to with remote: true.
For example in your view:
link_to "Activate", car_path(#car.id), method: :post, remote: true
And in your controller method:
def active
#car = Car.find(params[:id])
#car.update(active: true)
render json: :ok
end
A complete guide present here.
If you are using jquery, you can use jquery ajax method with dataType as JSON.
And you can also use the same restful update method i.e without creating any new method.
View -
<%= button_tag 'Activate', car_id: "22" , id: "activate_car" %>
Controller -
def update
#car = Car.find(params[:id])
respond_to do |format|
if #car.update(car_params)
format.html { redirect_to #car, notice: 'Car was successfully updated.' }
format.json { render :json: 'Successfully update' }
else
format.html { render :edit }
format.json { render json: #car.errors }
end
end
end
private
def car_params
params.require(:car).permit(:active)
end
JS -
$(document).on("click", '#activate_car', function () {
car_id = $(this).attr('car_id')
$.ajax({
url: "/cars/" + car_id,
type: "PUT",
data: {
active: true
},
dataType: "json",
success: function (response) {
alert(response)
}
});
});
I know I'm late but adding this answer for new rails developers
You simply need to use link_to with remote: true. If link_to throws routing error then use button_to instead
For example in your view:
button_to "Activate", car_path(#car.id), method: :patch, remote: true
And in your controller method:
def active
#car = Car.find(params[:id])
#car.update(active: true)
redirect_to cars_path(#cars), status: :see_other
end
And in your routes.rb :
resources :cars do
member do
patch :active
end
end

How to get the result when calling Ajax function

I need to get the email-id of the client when im clicking the person
name if his email-is is exist in db means by default it should need to
show
$("#user_employee_id").change(function(){
alert(1);
var user_id = $(this).val();
$.ajax({
type: "GET",
url: "/users/emailcheck",
data: { id: user_id }
}).success(function(res){
console.log(res);
$("#user_email").val(res.data["user"]["email"]);
});
});
controller.rb
def emailcheck
#user = User.find_by(id: params[:id])
if #user.present?
render :json => {:user => #user.to_json(:only => [:email]) }
end
end
After doing this also im not getting email can any one suggest me im
wrong, i need tan email-id when im clicking the person, i have 1400
data every one is having email-id please help me out how to get
corresponding employee name when im clicking i need to get thier mail
id bydefalut in mail-id textbox
Change the line in ajax
$("#user_email").val(res.data["user"]["email"]);
With
$("#user_email").val(res.email);
And in controller:
def emailcheck
#user = User.find_by(id: params[:id])
respond_to do |format|
if #user.present?
format.json { render json: {:email => #user.email} }
else
format.json { render json: {:email => " "} }
end
end
end

In Rails, how should I update a value in the database with ajax?

When the checkbox is ticked, I just want to update the 'Needed'value in the database.
And the script is list below
$('td div').find('input[type=checkbox]').click(function(){
$.ajax({
type: "PUT",
dataType: "script",
url: '/ecs/2',
contentType: 'application/json',
data: JSON.stringify({ ecs:{needed:'N'}, _method:'put' })
}).done(function( msg )
{
alert( "Data Saved: " + msg );
});
});
});
and the controller's code is standard.
# PATCH/PUT /ecs/1
# PATCH/PUT /ecs/1.json
def update
respond_to do |format|
if #ec.update(ec_params)
format.html { redirect_to #ec, notice: 'Ec was successfully updated.' }
format.json { head :no_content }
format.js
else
format.html { render action: 'edit' }
format.json { render json: #ec.errors, status: :unprocessable_entity }
format.js
end
end
end
The EC is the module's name, needed is the column's name. I just want to update a new value in the needed of ec with id=2 .
But right now, I always encountered the BAD REQUEST.
I'm not sure where is the problem.
for your checkbox (make it unobtrusive, it is just a quick example):
... onclick="$.post('/url', {omg_it_is_checked: $(this).attr('checked')})"
in routes.rb:
post '/url' => 'my_controller#my_action'
in controller:
def my_action
#....
#var = some.actions.here.with(params[:omg_it_is_checked]) #or update what you need
respond_to do |format|
format.js{render layout: false}
end
end
than you have to have an appropriate view my_action.js.erb with something like this:
$('#my_uniq_dom_id').html('<%= j render partial: 'new_piece_of_html' %>') #you can render nothing or flash something
and last we need is _new_piece_of_html.html.erb:
<div id="new_ajaxed_content"><%= #var %></div> <!-- or you can render checked checkbox, even with animation, or error message if in some reason it was not saved -->
voila! div#my_uniq_dom_id is updated with div#new_ajaxed_content after controller action
completely different approach - use this gem. it is simple solution for simple needs
cheers!

Rails: Manipulate rendered JSON when using UJS

I enhanced my app by allowing AJAX form submissions, using UJS. Here is my create#product action:
def create
if Product.create params[:product]
respond_to do |format|
message = "New product created."
format.html { redirect_to :back, :notice => message }
format.js { render :json => { :status => true, :message => message } }
end
end
end
But I'm figuring out how to handle outputted JSON in my views/products/create.js.erb file??
I tried this simple console.log example, but without success (I mean, no console output):
$(function(){
console.log(xhr.responseText);
});
Thanks in advance.
You could use:
$('form.new_product').bind('ajax:success',function(event, data, status, xhr){
});
$('form.new_product').bind('ajax:error',function(event, xhr, status, error){
});
or even $('form.new_product').on(same_args).
Just make sure new_product is the actual class of your form.

How to make AJAX responses work from the Rails side?

The HTML form:
<form id="newsletter" method="post" action="/subscribers" data-remote="true">
<label for="email">Enter your email:</label>
<input type="text" name="email" class="text" />
<p class="btn"><span>Signup</span></p>
</form>
Note the data-remote="true"
The Controller:
class SubscribersController < ApplicationController
def create
#subscriber = Subscriber.create(:email => params[:email],
:ip_address => request.remote_ip )
respond_to do |format|
format.js
end
end
end
The View (subscribers/create.js.erb)
no clue what goes here to make it return normal AJAX response (or error if it encountered one
1. What do i put in the view to make it return normal ajax response or error? -- Is it even needed to begin with (can I return this without creating such views)
2. Is this the correct way of doing ajax with Rails?
This looks exactly like a question that I just answered today for another user... same model names and everything.
def create
#subscriber = Subscriber.new(#your params)
respond_to do |format|
if #subscriber.save
format.js { render :json => #subscriber, :status => :created, :location => #susbscriber }
else
format.js { render :json => #susbcriber.errors, :status => :unprocessable_entity }
end
end
end
Also, you shouldn't have to do the unless Subscriber.find_by_email(params[:email]) in your controller. You should just add validates_uniqueness_of :email to the Subscriber model.
In the .erb file that contains the form, you would add the following javascript:
jQuery(function($) {
// create a convenient toggleLoading function
var toggleLoading = function() { $("#loading").toggle() };
$("#your-form")
.bind("ajax:loading", toggleLoading)
.bind("ajax:complete", toggleLoading)
.bind("ajax:success", function(event, data, status, xhr) {
$("#response").html(data);
});
.bind("ajax:failure", function(event, data, status, xhr) {
//your code
});
});
A standard respond_to block (this allows both html and js) would be:
respond_to do |format|
if #subscriber.save
format.html { redirect_to(#subscriber, :notice => 'Subscriber created.') }
format.js # Not redirecting, just spitting out the JSON(js?) response (I believe).
else
format.html { render :action => "new" }
format.js # Not redirecting for js and this time return error response.
end
end
So what you have actually looks ok to me. Is it working ok or is there an issue?
The above should work with rails2 and rails3. Rails3 has a more succint syntax (of course) but given you are Rails2 I'll leave that for now.

Resources