I need an employee email-id when I'm selecting his name, if his email id is exist in database. Can any one suggest me how to do, since I have 1400 employees and their mail id, I'm getting their names in dropdown but when I'm selecting their names I need their mail id to display in the particular field......
$("#user_employee_id").change(function(){
$.ajax({
type: "GET",
url: "/User/emailcheck",
data: { email: user.email }
});
});
user_controller.rb
def emailcheck
#user = User.search(params[:email])
end
user.rb
def self.search(email)
if email
where('email = ?',email).first
end
end
Can any one tell how to get the email id when I click on the employee name? I need to get email id of that employee by default in email tab.
Try this:
$("#user_employee_id").change(function(){
var id = $(this).val();
$.ajax({
type: "GET",
url: "/User/emailcheck",
data: { id : id}
success : function( data ) {
$("#user_email").val(data);
},
error : function(err) {
}
});
});
user_controller.rb
def emailcheck
#user = User.find_by_id(params[:id])
respond_to do |format|
if #user.email.present?
format.json { render json: #user.email , status: :ok }
else
format.json { render json: "No mail id", status: :unprocessable_entity }
end
end
end
You can do this like
Chenge your js Code like:
$("#user_employee_id").change(function(){
var user_id = $(this).val(); #considering that your are setting id as a value of select field
$.ajax({
type: "GET",
url: "/user/emailcheck",
data: { id: user_id }
}).success(function(res){
$("#your_text_field_id").val(res.text);
});
});
and in your user_controller.rb
def emailcheck
user = User.find_by(id: params[:id])
if user.present?
render text: user.email
end
end
Related
I recently deployed my site on Heroku and Netlify and was having issues with Auth. My current issue (and hopefully last) is that upon login, rails is sending back a user instance instead of the object with information (i.e #User:0x000056205efbbad8). I get a token from my rails response and upon refresh am logged in but am not automatically logged in because of the user instance being returned instead of an object with user information.
This is my auth controller
class AuthController < ApplicationController
def login
user = User.find_by(username: params[:username])
if user && user.authenticate(params[:password])
secret = ENV["SECRET_KEY_BASE"]
token = JWT.encode({ user_id: user.id }, secret, 'HS256')
render json: { user: UserSerializer.new(user), token: token }
else
render json: { failure: "Invalid Username or Password" }
end
end
def signup
auth_params = params.permit(:username, :password, :email, :avatar)
if params[:avatar].instance_of?(String) || params[:avatar].nil?
user = User.create(auth_params)
render json: user
else
imageUploaded = Cloudinary::Uploader.upload(params[:avatar])
user_params_new = auth_params
user_params_new[:avatar] = imageUploaded["url"]
user = User.create(user_params_new)
if user.valid?
secret = ENV["SECRET_KEY_BASE"]
token = JWT.encode({ user_id: user.id }, secret, 'HS256')
render json: {user: user, token: token }, status: :created
else
render json: { error: user.errors.full_messages }, status: :unprocessable_entity
end
end
end
end
Here is my login function on my React frontend
function handleLogin(e) {
e.preventDefault()
fetch(`${process.env.REACT_APP_API_BASE_URL}/login`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(loginData)
})
.then(r => r.json())
.then(data => {
if (data.failure) {
Swal.fire({
icon: 'error',
title: 'Oops...',
text: 'Incorrect Username or Password!'
})
} else {
setCurrentUser(data.user)
setUserReviews(data.user.reviews)
setFavorites(data.user.favorites)
localStorage.setItem("token", data.token)
history.push("/festivals")
}
})
}
I so appreciate any help on this, thanks so much!
Link to github repo: https://github.com/connormul/festie-backend
https://github.com/connormul/festie-frontend
render json: { user: UserSerializer.new(user), token: token }
This doesn't look a correct use of serializer
try to change it to
render json: { user: UserSerializer.new(user).as_json, token: token }
I use select2 and want to create new tags and then save them.
i have form for #cost and for select2 this
<%= f.collection_select :product_ids, Product.all,:id, :name ,{include_hidden: false},{ multiple: true} %>
for creation new product i have this js code
$(document).ready(function () {
$('#cost_product_ids').select2({
tags: true,
tokenSeparators: [",", " "],
createProduct: function (product) {
return {
id: product.term,
text: product.term,
isNew: true
};
}
}).on("change", function (e) {
var isNew = $(this).find('[data-select2-tag="true"]');
if (isNew.length) {
$.ajax({
type: "POST",
url: "/product_new",
data: {product: isNew.val()}
});
}
});
});
and controller method for save new product
def product_new
product = Product.find_by(name:params[:product])
Product.create(name:params[:product]) if !product
render json: :ok
end
cost create action
def create
#cost = Cost.new(costs_params)
if #cost.save
flash[:notice] = t('added')
if params[:add_more].present?
redirect_back(fallback_location: root_path)
else
redirect_to #cost
end
else
render action: 'edit'
end
end
def costs_params
params.require(:cost).permit(:day, :amount, :description, :source,:tag_list,:product_ids=>[])
end
it works ok, but when i want to save my #cost record with this newly created product i have received only name of my tag without id.
For example i have products water=>id:1,beer=>id:2,and create new juice tag in db it has id:3
on create in have params "product_ids"=>["1", "2", "juice"]
How to fix it?
you shouldn't use id: product.term,
but id: product.id,
I have a POST request from a javascript file below:
this.submitQuoteButton = $("<button />")
.text("Download PDF")
.addClass("submitQuoteButton button-success pure-button")
.click(function() {
$.ajax({
type: "POST",
url: "../quotes/create",
data: {
name : "John ",
email: "john#john.com",
json: "data",
uid: "uid",
},
dataType:'text',
success: function(data,status,xhr){
console.log(status);
alert("SUCCESS!");
},
error: function(xhr,status,error){
console.log(status,error);
alert("ERROR!");
}
});
})
This POST calls to my quotes_controller create method where I have this
def create
#quote = Quote.new(quote_params)
if #quote.save
redirect_to root_url
else
redirect_to blog_path
end
end
private
def quote_params
params.require(:quotes).permit(:uid, :name, :email, :json)
end
The aim is to get the data passed in the POST request and save it to my database with the create method. Am I doing this right? I am getting a:
param is missing or the value is empty for: quotes
Does this mean there is a problem with my database set up or the create method?
quote_params require the quotes key in your params. So your ajax call data should look like this:
data: {
quotes: {
name : "John ",
email: "john#john.com",
json: "data",
uid: "uid",
}
}
I am using angularjs-rails-resource and I have set up a service. I have a table of leagues which belongs_to a user so the columns of the league table are id, name, and user_id. I am trying to pull out all the leagues for a specified user.
Here's the code. Every time I use it I am getting all the leagues returned. I am pretty sure I don't have the service defined correctly. Any help would be greatly appreciated.
league_service.js
'use strict';
/* Services */
var ffpServices = angular.module('ffpServices', ['rails']);
ffpServices.factory('League', ['railsResourceFactory', function (railsResourceFactory) {
return railsResourceFactory({
url: '/api/v1/leagues',
name: 'league'
}); }]);
leagues_controller.js
'use strict';
/* Controllers */
var ffpControllers = angular.module('ffpControllers', []);
ffpControllers.controller('LeagueCtrl',
function ($scope, $routeParams, League) {
$scope.leagues = League.query({ user_id: $routeParams.userId });
$scope.leagues.then(function (results) {
$scope.leagues_data = [];
$scope.leagues_data = results;
$scope.lempty = false;
if ($scope.leagues_data.length < 1) {
$scope.lempty = true;
}
}, function (error) {
console.log(error);
});
});
leagues_controller.rb
class Api::V1::LeaguesController < ApplicationController
respond_to :json
def index
#leagues = League.all
render json: #leagues
end
def show
#league = League.find(params[:id])
render json: #league
end
def create
#league = current_user.leagues.new(league_params)
respond_to do |format|
if #league.save
format.json { head :created, location: league_path(#league) }
else
format.json { head :unprocessable_entity }
end
end
end
private
def league_params
params.require(:league).permit(:name)
end
end
I want send data from angularjs to rails server. For this, I have an angularjs service that I use GET,POST,DELETE,UPDATE method. I can use GET method, but for other method I cannot use, beacause I have to sent parameter to server, but I cannot do this.
record.js:
var app = angular.module('app');
app.controller('RecordCtrl',['$scope','Session','Records', function($scope, Session, Records){
$scope.records = Records.index();
}]);
recordService.js:
'use strict';
var app = angular.module('recordService', ['ngResource']);
//angular.module('recordService', ['ngResource'])
app.factory('Records', function($resource) {
return $resource('/api/record.json', {}, {
index: { method: 'GET', isArray: true},
create: { method: 'POST' }
});
})
.factory('Secure', function($resource){
return $resource('/api/record/:record_id.json', {}, {
show: { method: 'GET' },
update: { method: 'PUT' },
destroy: { method: 'DELETE' }
});
});
and I get data in rails server by below code:
class Api::V1::RecordController < Api::V1::BaseController
def index
respond_with(Record.all)
end
def show
#data = Record.find(params[:id]).to_json()
respond_with(#data)
end
def update
#data = Record.find(params[:id])
respond_to do |format|
if #data.update_attributes(record_params)
format.json { head :no_content }
else
format.json { render json: #data.errors, status: :unprocessable_entity }
end
end
end
def create
#data = Record.create(record_params)
#data.save
respond_with(#data)
end
def destroy
#data = Record.find(params[:id])
#data.destroy
respond_to do |format|
format.json { head :ok }
end
end
private
def record_params
params.require(:record).permit(:name)
end
end
I don't know how can I send method from angularjs controller to rails server. I try below code, but I don't successful:
Records.create(function() {
//"name" is the name of record column.
return {name: test3};
});
but I get below error in rails server:
Started POST "/api/record.json" for 127.0.0.1 at 2014-08-30 17:55:27 +0430
Processing by Api::V1::RecordController#create as JSON
How can I fix this problem? How can I send parameter to rails server?
I want send delete method to rails server. I know I have to send record.id to server, I use below type:
//type 1
var maskhare = { record_id: 4};
Secure.destroy(function(){
return maskhare.json;
});
//type 2
Secure.destroy(4);
but I get below error in server:
Started DELETE "/api/record" for 127.0.0.1 at 2014-08-30 19:01:21 +0430
ActionController::RoutingError (No route matches [DELETE] "/api/record"):
I fix correct url in recordService.js, but I don't know why request is send to before url again. Where is the problem?
It looks like you are successfully making a request, the last line there says that a POST request was made and went to the right controller and action.
The problem is strong parameters. You need to add name to the filtered parameters list.
private
def record_params
params.require(:record).permit(:secure, :name)
end
Also rails expects the parameters in the following format: { record: {name: 'something"} }
To fix your second problem
I would try to follow this recipe
Replace your code with this:
app.factory("Secure", function($resource) {
return $resource("/api/record/:id", { id: "#id" },
{
'show': { method: 'GET', isArray: false },
'update': { method: 'PUT' },
'destroy': { method: 'DELETE' }
}
);
});
and then
Secure.destroy({id: 4});
Keep in mind that if you add respond_to :json in your controller then you can omit the .json in the URLs. Like so:
class Api::V1::RecordController < Api::V1::BaseController
respond_to :json
...
end