I want to get data(customer ID) from the Stripe webhook then save it to my db, I get the data but the problem is customer_id is still nil on my db. Here's my code
StripeEvent.configure do |events|
events.all do |event|
if event.type == 'customer.created'
customer = event.data.object
user = User.where('customer_id LIKE ?', "%#{customer['id']}%").first
if user
customer = Stripe::Customer.retrieve(JSON.parse(user.customer_id)['id'])
user.customer_id = customer.to_json
user.save!
end
end
end
end
This code :
user = User.where('customer_id LIKE ?', "%#{customer['id']}%").first
gives this output:
SELECT "users".* FROM "users" WHERE (customer_id LIKE '%cus_EEIReNX3M4je2U%') ORDER BY "users"."id" ASC LIMIT
And when I get to my db, my customer_id field is still nil, here's the output:
<User id: 3, email: "achielinda44#yahoo.com", created_at: "2018-12-27 03:47:41", updated_at: "2018-12-27 03:47:41", first_name: "Achie", last_name: nil, gender: nil, gender_preferences: nil, description: "trial stripe", photo: nil, provider: nil, uid: nil, name: nil, image: nil, customer_id: nil>
Can anyone please see something that I'm missing out on? I will really appreciate the help. Thanks!
My code was all wrong, not all though. The user object was nil because I was trying to get a customer_id that was not yet available, so I got the user using email, then passed the stripe customer id to them then finally saved them. It worked!
StripeEvent.configure do |events|
events.all do |event|
if event.type == 'customer.created'
customer = event.data.object
user = User.find_by(email: customer.email)
if user
user.customer_id = customer.id
user.save!
end
end
end
Related
How to add one record's value to the another record's value at the end as key and value.
#data = UserPost.
includes(:user_likes, :comments).
where('user_likes.flag = ?', false).
where("#{#data1.values.join(' ')}").
order('user_likes.created_at DESC').
references(:user_likes :comments, :m_user_detail).
paginate(page: params[:page], per_page: 50)
output of above query
# id: 1,
# user_id: "001",
# user_o_id: nil,
# message: "completeļ¼",
# o_id: nil,
# o_name: nil,
# image_name: "image.jpeg",
# image_content_type: "image/jpeg"
add data of below query to above query at the end last_name and first_name
#data2 = UserDetail.select('user_id, last_name, first_name').where("user_id IN (?)", #userlist)
# user_id: "001", last_name: "shinde", first_name: "rohit"
# user_id: "037534", last_name: "mane", first_name: "pravin"
Does including user & user_details in your query help? Checkout the code below
#data = UserPost.
includes(:user_likes, :comments, user: [:user_details]).
where('user_likes.flag = ?', false).
where("#{#data1.values.join(' ')}").
order('user_likes.created_at DESC').
references(:user_likes :comments, :m_user_detail).
paginate(page: params[:page], per_page: 50)
Now you should be able to access user's name from user_details table
#data.first.user.user_details.last_name # shinde
I am using action mailer to email winners, #result array has records of participants who has won including their email.
#result=>[#<Participant id: 47, admin_id: nil, sweepstake_id: 8, participant_name: "gomez", participant_email: "rakesh.k#birdvision.in", participant_number: "12131245421", ip_addr: "127.0.0.1", answer: "nice", reg_time: nil, entry_opt_id: nil, created_at: "2015-09-03 12:15:48", updated_at: "2015-09-07 12:12:53">, #<Participant id: 47, admin_id: nil, sweepstake_id: 8, participant_name: "gomez", participant_email: "rakesh.k#birdvision.in", participant_number: "12131245421", ip_addr: "127.0.0.1", answer: "nice", reg_time: nil, entry_opt_id: nil, created_at: "2015-09-03 12:15:48", updated_at: "2015-09-07 12:12:53">]
But when i pass the result from my controller to the mailer, the result now only has id as string.
Parameters: {"result"=>["47", "47"]}.
How can i pass the array result which has all the participant records?
Code in view page:
<%= link_to "Email Winners",email_winner_sweepstakes_path(:result=>#result) %>
Code in controller:
def email_winner
Rails.logger.info("***********************#{params.inspect}")
ParticipantMailer.winner_confirmation(params[:result]).deliver_now!
end
Code in mailer:
def winner_confirmation(result)
#result = result
#url = 'http://example.com/login'
Rails.logger.info("=================mailer=================")
Rails.logger.info(#result.inspect)
#result.each do |i|
mail(to: i.participant_email, subject: 'Congratulation')
end
end
You will have to find winners by ID, in this line:
<%= link_to "Email Winners", email_winner_sweepstakes_path(result: #result) %>
what you do is formulate the URL and you can't store objects its only string and what it did is it will call .id on #result
to fix that:
in your controller:
def email_winner
#results = Participant.where("id in (?)", params[:result])
ParticipantMailer.winner_confirmation(#results).deliver_now!
end
You cannot pass ruby objects in links, because that triggers a new page load on a different URI, and the ids are provided in that address. You need to only pass ids.
Therefore your ids being passed here, you can fetch the objects with the following:
#result.each do |id|
participant = Participant.find(id)
mail(to: participant.participant_email, subject: 'Congratulation')
end
So in my wiki model I have an attribute for private. If private is true then the wiki should not be viewable to users who are not assign to the wiki_ids via a HABTM relationship.
wiki.rb:
class Wiki
include Mongoid::Document
include Mongoid::Timestamps
has_and_belongs_to_many :users
field :title, type: String
field :body, type: String
field :private, type: Boolean, default: false
scope :visible_to, ->(user) {
user.present? || user.blank? ?
where(:private => false) : where(:private => false).or(:id => user.wiki_ids)
}
def public?
!self.private?
end
end
WikisController:
def index
##wikis = policy_scope(Wiki)
##wikis = Wiki.all
#wikis = Wiki.visible_to(current_user)
authorize #wikis
end
def show
#wiki = Wiki.find(params[:id])
end
def new
#wiki = Wiki.new
authorize #wiki
end
def create
#wiki = current_user.wikis.build(params.require(:wiki).permit(:title, :body, :private, :user))
authorize #wiki
if #wiki.save
flash[:notice] = "Wiki was saved."
redirect_to #wiki
# report success
else
flash[:error] = "There was an error saving your wiki. Please try again."
render :new
end
I'm pretty confident its the scope that needs to be modified in the model, because if i comment out the scope in the model and replace the index in the controler to Wiki.all. I see all the wikis.
As of right now as somebody who created the wiki plus flagged it private and I am logged in I do not see that wiki nor does anybody that I add as a user to the wiki.
I tried adding other conditions to the end such as user.present? ? where(:id => user.wiki_ids) and user.present? && where(:id => user.wiki_ids) but just get errors thrown back at me.
DB entry for User:
User_id: 547eb8867261691268000000, wiki_ids: [BSON::ObjectId('54807226726 1690be0260000'),
BSON::ObjectId('5480735c7261690bae000000'), BSON::ObjectId('548
136e57261690aef000000'), BSON::ObjectId('5489af337261690d95000000'),
BSON::Objec tId('5489b57e7261690d95010000'),
BSON::ObjectId('548f9f607261690bb5060000'), BSO
N::ObjectId('54908f127261690be8000000'),
BSON::ObjectId('54908f207261690be801000 0')], name: "Carey VonRueden",
email: "admin#email.com", encrypted_password: "$2a
$10$NrlQ2XH64UucOPcI1aje9.57eoSO74676264YrIjfGvncyGcpGWy",
reset_password_token : nil, reset_password_sent_at: nil,
remember_created_at: nil, sign_in_count: 7, current_sign_in_at:
2014-12-17 18:51:15 UTC, last_sign_in_at: 2014-12-16 02:38:5 8 UTC,
current_sign_in_ip: "10.0.2.2", last_sign_in_ip: "10.0.2.2",
confirmation
_token: nil, confirmed_at: 2014-12-03 07:15:18 UTC, confirmation_sent_at: nil, u nconfirmed_email: nil, role: "admin">
DB entry for Wiki:
Wiki _id: 54908f207261690be8010000, created_at: 2014-12-16 19:59:28 UTC, updated_at: 2014-12-16 19:59:28 UTC, user_ids:
[BSON::ObjectId('547eb886726169126 8000000')], title: "Private", body:
"Private", private: true>
your scope condition is wrong
user.present? || user.blank? -> this will be true always. if user is present or user is blank, it will always return only the public wikis
Change your scope to something like below.(assuming you want all public wiki's if user is not signed in. If user is signed in, you want public + the wikis created by user)
scope :visible_to, ->(user) {
user.nil? ? where(:private => false) : where(:private => false).or(:id => user.wiki_ids)
}
If you are still not getting what you are expecting, check if user.wiki_ids is returning the right values
I use this logic in my app:
controller
#current_user = User.find_or_create_from_oauth(auth_hash)
user.rb
def self.find_or_create_from_oauth(auth_hash)
provider = auth_hash["provider"]
uid = auth_hash["uid"].to_s
case provider
when 'twitter'
if user = self.find_by_twitter_uid(uid)
return user
else
return self.create_user_from_twitter(auth_hash)
end
end
end
def self.create_user_from_twitter(auth_hash)
a = self.create({
:twitter_uid => auth_hash["uid"],
:name => auth_hash["info"]["name"]
})
puts a.inspect
user = User.find_by_twitter_uid(a.twitter_uid)
puts '---'
puts user.inspect
end
Immediately after self.create I would need to run this line:
Assignment.create(:user_id => a.id, :role_id => 2)
The problem is, that the line puts user.inspect return something like this:
#<User id: nil, name: "...name...", twitter_uid: "96580821", provider: "twitter", created_at: nil, updated_at: nil>
Why is in the hash returned id: nil?
Or, is there any other way, how to get the ID of last created record?
If the user has been correctly saved, you can use directly a:
a.assignments.create(:role_id => 2)
Otherwise (check using create! instead of create) there may be a validation error.
I have this method
def last_board
user = current_user #current_user
boards = current_user.boards #return every boards that belongs to current_user e.g. [#<Board _id: 4f2968ac1d41c81c7c000063, _type: "Board", created_at...]
followers = user.all_followers #return every followers of user [#<User _id: 4f2862b21d41c847e200005b, _type: "User" reset_password_sent_at: nil, confirmation_token: nil,...]
followers.each do |follower|
boards.each do |board|
# I want to be a follower of user, if I am following at least one board of this user
#I want run this code, "follower.unfollow(user)", only if follower does not following any user's board.
#this method "follower.follower_of?(board)" return true or false if follower follow board
end
end
you can something like this
followers.each do |follower|
is_having_any_board = false
follower.boards.each do |follower_board|
boards.each do |board|
if(follower_board.id == board.id)#delete last )
is_having_any_board = true
break;
end
end
end
if(is_having_any_board)
follower.follow(user)
else
follower.unfollow(user)
end
end