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
Related
I'm trying to update an Idea attribute challenge_id through a hidden form field. Here is the field:
<%= f.hidden_field :challenge_id, :value => #challenge.id %>
It successfully passes the challenge id as a param when an idea is created to the Idea Controller#create method:
Started POST "/ideas.js" for ::1 at 2015-06-18 15:39:49 -0400
Processing by IdeasController#create as JS
Parameters: {"utf8"=>"✓", "idea"=>{"title"=>"adsf", "description"=>"asf", "domain_tokens"=>"20", "challenge_id"=>"5"}, "commit"=>"Create Idea"}
This challenge_id => 5 should then be saved to the idea in the line #idea = Idea.new(idea_params) below:
ideas_controller.rb
def create
#idea = Idea.new(idea_params)
respond_to do |format|
if #idea.save
idea_count = #idea.user.ideas_created_count
#idea.user.update(:ideas_created_count => idea_count + 1)
#idea.domains.each do |domain|
current_user.add_points(1, category: domain.title)
end
#ideas = current_user.current_team.ideas.sort_by{|i| i.heat_index}.reverse
#ideas = #ideas.paginate(:page => params[:ideas_page], :per_page => 10)
format.html { redirect_to :back, notice: 'Idea was successfully created.' }
format.json { render :show, status: :created, location: #idea }
format.js
else
format.html { redirect_to :back, notice: "You must attach domains to your Idea." }
format.json { render json: #idea.errors, status: :unprocessable_entity }
format.js { render :create_failed }
end
end
end
.
.
def idea_params
params.require(:idea).permit(:title, :description, :challenge_id)
end
However, this challenge id isn't being saved to the idea with the other permitted idea_params, :title and :description. How can I get challenge_id to be saved to the Idea when it's created?
Instead of using hidden field, why not pass in the challenge_id in your form? Otherwise, you leave open the possibility that users can enter whatever they want in that hidden field.
Form:
form_for [#challenge, Idea.new] do |f|
And then:
def create
#challenge = Challenge.find(params[:challenge_id])
#idea = Idea.new(idea_params)
#idea.challenge_id = #challenge.id
end
I'm assuming you have challenge_id column in ideas table.
Try something like:
def create
#idea = Idea.new(idea_params)
#idea.challenge_id = params[:idea][:challenge_id]
#...
end
If you params or column you want to save it to is different, make sure to make the change, but you get the idea.
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
I want to get data from client side,and display in my ror website using post method in create method,how to write the function for fetching data from client side(android) to ror.
def create
#post = Post.new(params[:post])
data_json = JSON.parse request.body.read
#respond_to do |format|
if #post.save
flash[:notice] = "Prayer Successfully created."
#posts = Post.paginate(page: params[:page],:per_page => 5)
#post = Post.new(data_json)
#post.save
#format.json{ render :json => #post, :status => :created }
else
flash[:notice] = "Error"
#posts = Post.paginate(page: params[:page],:per_page => 5)
#format.json{ render :json => #post, :status => :created }
end
end
There is not enough data in your question but ill try to help you.
Your client-side logic should look like that (jQuery code):
$("#some_button").bind("click", function(event){
$.ajax({
type: "POST",
url: "/bla-bla/create",
data: { my_param: JSON.stringify(my_data) }
});
});
And action of controller that match to route /bla-bla/create:
def create
my_var = JSON.parse(params[:my_param])
...
#do what you want with "my_var"
Hope it'll help you!
I am testing an Invoice model (a Client has many invoices, an Invoice belongs to a Client) and trying to check whether the create method works.
This is what I have come up with:
before do
#valid_invoice = FactoryGirl.create(:invoice)
#valid_client = #valid_invoice.client
end
it "creates a new Invoice" do
expect {
post :create, { invoice: #valid_client.invoices.build(valid_attributes), client_id: #valid_client.to_param }
}.to change(Invoice, :count).by(1)
end
This is my invoice factory:
FactoryGirl.define do
factory :invoice do
association :client
gross_amount 3.14
net_amount 3.14
number "MyString"
payment_on "2013-01-01"
vat_rate 0.19
end
end
This is the create method in the invoices_controller:
def create
#client = Client.find(params[:client_id])
#invoice = #client.invoices.build(params[:invoice])
respond_to do |format|
if #invoice.save
format.html { redirect_to([#invoice.client, #invoice], :notice => 'Invoice was successfully created.') }
format.json { render :json => #invoice, :status => :created, :location => [#invoice.client, #invoice] }
else
format.html { render :action => "new" }
format.json { render :json => #invoice.errors, :status => :unprocessable_entity }
end
end
end
And these are the valid attributes, ie the attributes needed for an invoice to be created successfully:
def valid_attributes
{
gross_amount: 3.14,
net_amount: 3.14,
number: "MyString",
payment_on: "2013-01-01",
vat_rate: 0.19
}
end
These are all valid. Maybe the client_id is missing?
It is only telling me that the count did not change by one - so I am not sure what the problem is. What am I doing wrong?
#gregates - Your answer was right, why did you remove it? :-) Post it again and I will check it as best answer.
This is the solution:
post :create, { invoice: valid_attributes, client_id: #valid_client.to_param }, valid_session
instead of
post :create, { invoice: #valid_client.invoices.build(valid_attributes), client_id: #valid_client.to_param }
in the test.
Also, I had to change the number in the valid_attributes. Debugging every single validation showed me that it was the same as in the factory - but must instead be unique. This solved it for me! Thanks for everyone's help!
The following attempt_login method is called using Ajax after a login form is submitted.
class AccessController < ApplicationController
[...]
def attempt_login
authorized_user = User.authenticate(params[:username], params[:password])
if authorized_user
session[:user_id] = authorized_user.id
session[:username] = authorized_user.username
flash[:notice] = "Hello #{authorized_user.name}."
redirect_to(:controller => 'jobs', :action => 'index')
else
[...]
end
end
end
The problem is that redirect_to doesn't work.
How would you solve this ?
Finally, I just replaced
redirect_to(:controller => 'jobs', :action => 'index')
with this:
render :js => "window.location = '/jobs/index'"
and it works fine!
There is very easy way to keep the flash for the next request. In your controller do something like
flash[:notice] = 'Your work was awesome! A unicorn is born!'
flash.keep(:notice)
render js: "window.location = '#{root_path}'"
The flash.keep will make sure the flash is kept for the next request.
So when the root_path is rendered, it will show the given flash message. Rails is awesome :)
I think this is slightly nicer:
render js: "window.location.pathname='#{jobs_path}'"
In one of my apps, i use JSON to carry on the redirect and flash message data. It would look something like this:
class AccessController < ApplicationController
...
def attempt_login
...
if authorized_user
if request.xhr?
render :json => {
:location => url_for(:controller => 'jobs', :action => 'index'),
:flash => {:notice => "Hello #{authorized_user.name}."}
}
else
redirect_to(:controller => 'jobs', :action => 'index')
end
else
# Render login screen with 422 error code
render :login, :status => :unprocessable_entity
end
end
end
And simple jQuery example would be:
$.ajax({
...
type: 'json',
success: functon(data) {
data = $.parseJSON(data);
if (data.location) {
window.location.href = data.location;
}
if (data.flash && data.flash.notice) {
// Maybe display flash message, etc.
}
},
error: function() {
// If login fails, sending 422 error code sends you here.
}
})
Combining the best of all answers:
...
if request.xhr?
flash[:notice] = "Hello #{authorized_user.name}."
flash.keep(:notice) # Keep flash notice around for the redirect.
render :js => "window.location = #{jobs_path.to_json}"
else
...
def redirect_to(options = {}, response_status = {})
super(options, response_status)
if request.xhr?
# empty to prevent render duplication exception
self.status = nil
self.response_body = nil
path = location
self.location = nil
render :js => "window.location = #{path.to_json}"
end
end
I didn't want to modify my controller actions so I came up with this hack:
class ApplicationController < ActionController::Base
def redirect_to options = {}, response_status = {}
super
if request.xhr?
self.status = 200
self.response_body = "<html><body><script>window.location.replace('#{location}')</script></body></html>"
end
end
end