Here, I'm defining a recipient by the params.
What if I want to send the message to all the users who has confirmed already at once?
How can I write?
Anyone has any idea?
controller
recipient = User.find_by_username(params[:messages][:recipient])
if recipient.confirmed_at.nil?
redirect_to messages_sent_path
flash[:notice] = "This user hasn't confirmed yet!"
return
end
params[:messages][:subject] = 'no subject' if params[:messages][:subject].blank?
subject = params[:messages][:subject]
body = params[:messages][:body]
if current_user != recipient
current_user.send_message(recipient, body, subject)
redirect_to :controller => 'messages', :action => 'sent'
flash[:notice] = "Sent!"
else
redirect_to :controller => 'messages', :action => 'received'
flash[:notice] = "Cannot send to yourself!"
end
If you're using mysql / sqlite3
users = User.where('confirmed_at IS NOT NULL')
users.each do |user|
current_user.send_message(user, body, subject)
end
Related
i have login page with 2 sessions client and admin so when client logged in i do redirect to complete the form and when admin logged in i redirect him to dashboard, the problem is :
ActionController::DoubleRenderError (Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".)
def login
#institute = Configuration.find_by_config_key("LogoName")
available_login_authes = FedenaPlugin::AVAILABLE_MODULES.select{|m| m[:name].classify.constantize.respond_to?("login_hook")}
selected_login_hook = available_login_authes.first if available_login_authes.count>=1
if selected_login_hook
authenticated_user = selected_login_hook[:name].classify.constantize.send("login_hook",self)
else
if request.post? and params[:user]
#user = User.new(params[:user])
user = User.find_by_username #user.username
if user.present? and User.authenticate?(#user.username, #user.password)
authenticated_user = user
end
end
end
if authenticated_user.present?
successful_user_login(authenticated_user) and return
elsif authenticated_user.blank? and request.post?
flash[:notice] = "#{t('login_error_message')}"
end
end
private
def successful_user_login(user)
session[:user_id] = user.id
flash[:notice] = "#{t('welcome')}, #{user.first_name} #{user.last_name}!"
redirect_to session[:back_url] || {:controller => 'user', :action => 'dashboard'}
if user.client
redirect_to session[:back_url] || {:controller => 'client', :action => 'complete_registration'}
end
end
end
You said right redirect_to is not a return method, the codes above is executed too. In you successful_user_login if user is client, you are calling redirect_to twice, so you can refactor this method to:
if user.client
redirect_to session[:back_url] || {:controller => 'client', :action => 'complete_registration'}
else
redirect_to session[:back_url] || {:controller => 'user', :action => 'dashboard'}
end
ActionController::DoubleRenderError is a error thrown by Ruby on Rails when a controller action tries to render or redirect a response twice. In your code, the action attempts to redirect the user to both 'user/dashboard' and 'client/complete_registration' depending on the user's status as a client. This will result in a DoubleRenderError. Notice that rendering or redirecting do not returns from the method.
Here are some untested code examples with different approaches:
You can calculate the controller and the action before calling redirect_to:
def successful_user_login(user)
session[:user_id] = user.id
flash[:notice] = "#{t('welcome')}, #{user.first_name} #{user.last_name}!"
controller, action = if user.client
["client", "complete_registration"]
else
["user", "dashboard"]
end
redirect_to session[:back_url] || {controller: controller, action: action}
end
You can also do an if and return after first redirect_to:
def successful_user_login(user)
session[:user_id] = user.id
flash[:notice] = "#{t('welcome')}, #{user.first_name} #{user.last_name}!"
if user.client
redirect_to session[:back_url] || {:controller => 'client', :action => 'complete_registration'}
return
end
redirect_to session[:back_url] || {:controller => 'user', :action => 'dashboard'}
end
Or do an if else:
def successful_user_login(user)
session[:user_id] = user.id
flash[:notice] = "#{t('welcome')}, #{user.first_name} #{user.last_name}!"
if user.client
redirect_to session[:back_url] || {:controller => 'client', :action => 'complete_registration'}
else
redirect_to session[:back_url] || {:controller => 'user', :action => 'dashboard'}
end
end
Completely banging my head against the wall trying to figure out how to cancel a user subscription. I have been all through StackOverflow and cant seem to find anything to help. Because I am fairly new to RoR the Stripe API only confuses me a bit more. I do understand that I need to capture and save the user ID somehow before i can cancel. I have not been able to figure this out...hence why i cant cancel subscriptions. HELP PLEASE
Subscribe_controller.rb
class SubscribeController < ApplicationController
before_filter :authenticate_user!
def new
unless (params[:plan_id] == '1' || params[:plan_id] == '2' || params[:plan_id] == '3')
flash[:notice] = "Please select a plan to sign up."
redirect_to new_subscribe_path
end
end
def update
# Amount in cents
token = params[:stripeToken]
customer = Stripe::Customer.create(
:email => current_user.email,
:card => token,
plan: params[:id]
)
current_user.subscribed = true
current_user.stripe_id = customer.id
current_user.save
redirect_to demo_path, notice: "Your Plan was created. Enjoy the demo!"
end
def cancel_plan
#user = current_user
if #user.cancel_user_plan(params[:customer_id])
#user.update_attributes(customer_id: nil, plan_id: 1)
flash[:notice] = "Canceled subscription."
redirect_to pricing_path
else
flash[:error] = "There was an error canceling your subscription. Please notify us."
redirect_to edit_user_registration_path
end
end
def update_plan
#user = current_user
if (params[:user][:stripe_id] != nil) && (params[:plan] == "2")
#user.update_attributes(plan_id: params[:plan], email: params[:email], stripe_id: params[:user][:stripe_id])
#user.save_with_payment
redirect_to edit_user_registration_path, notice: "Updated to premium!"
else
flash[:error] = "Unable to update plan."
redirect_to :back
end
end
end
User_controller.rb
class UsersController < ApplicationController
before_action :authenticate_user!
def update
if current_user.update_attributes(user_params)
flash[:notice] = "User information updated"
redirect_to edit_user_registration_path
else
flash[:error] = "Invalid user information"
redirect_to edit_user_registration_path
end
end
private
def user_params
params.require(:user).permit(:name)
end
end
Edit User Info Page
<div class="col-md-9 text-center">
<h2>Manage Plan</h2>
</div>
<div class="text-center">
<%= button_to "Cancel my account", cancel_plan_path, :data => { :confirm => "Are you sure?" }, :method => :delete, class: "btn btn-danger" %>
<button class="btn-lg btn btn-primary" disabled="disabled">Update Plan</button>
</div>
Routes.rb
get 'cancel_plan' => 'subscribe#cancel_plan'
resources :subscribe
devise_for :users
I am sure that you have seen this before stripe cancel subscription
first you have to get the customer the you can find there subscriptions so you can delete it
# Definition
customer = Stripe::Customer.retrieve({CUSTOMER_ID})
customer.subscriptions.retrieve({SUBSCRIPTION_ID}).delete
# Example
require "stripe"
Stripe.api_key = "sk_test_fSaKtH5qZMmhyXiF7YXup2wz"
customer = Stripe::Customer.retrieve("cus_5LXt66ikj5nYz5")
# customer.subscriptions returns a list of all subscriptions
customer.subscriptions.retrieve("sub_5TGMEBBALjNcD6").delete
Ultimate Answer
token = params[:stripeToken]
customer = Stripe::Customer.create(
:email => current_user.email,
:card => token,
plan: params[:id]
)
current_user.subscribed = true
current_user.stripe_id = customer.id
current_user.stripe_subscription_id = customer.subscriptions['data'][0].id
current_user.plan_name = customer.subscriptions['data'][0].plan.name
current_user.save
redirect_to demo_path, notice: "Your Plan was created. Enjoy the demo!"
In order to make this easier, you need to store the stripe_id and subscription_id in your database. Hence, after creating the columns stripe_id and subscription_id in your User model, you will have to save that:
customer = Stripe::Customer.create({
email: params[:stripeEmail],
source: params[:stripeToken],
plan: params[:plan]
})
subscription_id = customer.subscriptions['data'][0].id
user.update_attributes(stripe_id: customer.id, subscription_id: subscription_id)
Now you can always call the user's subscription since you have its id:
user = current_user
stripe_subscription = Stripe::Subscription.retrieve(user.subscription_id)
stripe_subscription.delete
If you only have the customer_id in your database, you can:
user = current_user
stripe_customer = Stripe::Customer.retrieve(user.stripe_id)
stripe_subscription = stripe_customer.['data'][0].delete
I am trying to use a specific controller action to redirect the user to the registration page, but it's not working.
In my users_controller.rb, I have:
def pre_approved_with_code_action
#code = params[:code]
if params[:commit] = 'Cancel'
redirect_to root_url
return
end
if params[:commit] = 'Create Account'
flash[:notice] = 'Please register as a new user'
redirect_to new_user_registration_path(:discount_code => #code)
return
end
if params[:commit] = 'Login And Retry'
redirect_to new_user_registration_path(:notice => 'Please register as a new user', :discount_code => #code)
return
end
end
The log file says:
Started POST "/pre_approved_with_code_action" for 127.0.0.1 at 2013-06-20 10:05:43 -0700
Processing by UsersController#pre_approved_with_code_action as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"sWENK4ZhisSKHQswUZkDcq8ZxsXU+ym9wQqnYwgPIo4=", "code"=>"SPK_2014", "commit"=>"Create Account"}
Redirected to http://localhost:3000/
So, it's redirecting to root_url, not new_user_registration_path. Any ideas?
Simple mistake, you need 2 equals signs
instead of if params[:commit] = 'Cancel' it should be if params[:commit] == 'Cancel'
def pre_approved_with_code_action
#code = params[:code]
if params[:commit] == 'Cancel'
redirect_to root_url
return
end
if params[:commit] == 'Create Account'
flash[:notice] = 'Please register as a new user'
redirect_to new_user_registration_path(:discount_code => #code)
return
end
if params[:commit] == 'Login And Retry'
redirect_to new_user_registration_path(:notice => 'Please register as a new user', :discount_code => #code)
return
end
end
Condition should have ==. = always evaluates to true if the right hand side is a non null value
I need to verify User data before_save. I'm saving only paypal_email, and don't save first and last name.
I added before_save filter in my model:
attr_accessible :paypal_email, :first_name, :last_name
attr_accessor :first_name
attr_accessor :last_name
before_save :verify
and added veify method:
protected
def verify
require 'httpclient'
require 'xmlsimple'
clnt = HTTPClient.new
header = {"X-PAYPAL-SECURITY-USERID" => "1111111111",
"X-PAYPAL-SECURITY-PASSWORD" => "111111",
"X-PAYPAL-SECURITY-SIGNATURE" => "11111",
"X-PAYPAL-REQUEST-DATA-FORMAT" => "NV",
"X-PAYPAL-RESPONSE-DATA-FORMAT" => "XML",
"X-PAYPAL-APPLICATION-ID" => "APP-2J632856DC989803F"
}
logger.info(#user.first_name)
data = {"emailAddress" => self.paypal_email,
"firstName"=> self.first_name,
"lastName" => self.last_name,
"matchCriteria" => "NAME",
"requestEnvelope.errorLanguage" => "en_US"}
uri = "https://svcs.paypal.com/AdaptiveAccounts/GetVerifiedStatus"
res = clnt.post(uri, data, header)
#xml = XmlSimple.xml_in(res.content)
if res.status == 200
if #xml['accountStatus']!=nil
account_status = #xml['accountStatus'][0]
if account_status == "VERIFIED"
redirect_to :back
flash[:success] = "Your account is verified"
else
redirect_to :back
flash[:error] = res.content
end
else
redirect_to :back
flash[:error] = res.content
end
else
flash[:error] = "Oops! Can't conntect to PayPal"
end
end
EDIT
def create
#user = User.new(params[:user])
if #user.valid?
#user.save
flash[:notice] = "success"
else
render :new
flash[:error] = "error"
end
what give me error:
undefined method `first_name' for nil:NilClass
Where is my error ?
Since you're in your model, replace #user.first_name with self.first_name or even first_name
Other issues
third party service calls should live in background jobs.
point flash is unknown in models, it belongs to controller, as well as redirect.
redirect_to :back, is not that a good practice: some browsers don't send the referrer
i get a AbstractController::DoubleRenderError in TicketsController#update.
If i select a particular user, the update is not happening.
def update
#selected_group = Group.find_by_id(params[:Department]) unless params[:Department].nil?
#selected_company = Company.find_by_id(params[:Company]) unless params[:Company].nil?
#ticketnote_content = params[:Ticketnote]
if ((#selected_group != nil) && (#selected_company != nil))
map_group_to_department
map_user_to_staff
update_ticket
if (#response['response'] == "Failed")
flash[:error] = response['err_desc']
redirect_to "/ticket/#{params[:id]}/edit"
return
elsif (#response['response'] == "Success")
#ticketnote_content
if #ticketnote_content != ""
add_note_to_ticket
end
map_assets_findings_tickets
flash[:notice] = "Succesfully updated the ticket"
TicketHistory.create_ticket_history(#assigned_user,#selected_asset,#ticket_params,current_user,#updated_ticket_response,"Updated")
end
else
flash[:error] = "Company or department can't be blank."
redirect_to "/ticket/#{params[:id]}/edit"
return
end
redirect_to :controller => 'tickets' , :action => 'show', :id => params[:id],:test_id => #test,:ticket_id=> params[:ticket_id]
end
As you have already used redirect_to within your if else statement and after execution of if else you are redirecting again, which lead this error(you can use only once within each action). In order to resolve this, I would suggest following solutions(the question was not clear, so I may not be right):
Solution 1: If your last redirect_to is not required then delete it, i.e.
redirect_to :controller => 'tickets' , :action => 'show', :id => params[:id],:test_id => #test,:ticket_id=> params[:ticket_id]
Solution 2: Update with and return in every redirect_to and moving you last redirect_to in your successful response condition(I'm not sure where you want your Ticket#show) , i.e.
def update
#selected_group = Group.find_by_id(params[:Department]) unless params[:Department].nil?
#selected_company = Company.find_by_id(params[:Company]) unless params[:Company].nil?
#ticketnote_content = params[:Ticketnote]
if #selected_group && #selected_company
map_group_to_department
map_user_to_staff
update_ticket
if (#response['response'] == "Failed")
flash[:error] = response['err_desc']
redirect_to "/ticket/#{params[:id]}/edit"
elsif (#response['response'] == "Success")
add_note_to_ticket if #ticketnote_content != ""
map_assets_findings_tickets
flash[:notice] = "Succesfully updated the ticket"
TicketHistory.create_ticket_history(#assigned_user,#selected_asset,#ticket_params,current_user,#updated_ticket_response,"Updated")
redirect_to :controller => 'tickets' , :action => 'show', :id => params[:id],:test_id => #test,:ticket_id=> params[:ticket_id]
end
else
flash[:error] = "Company or department can't be blank."
redirect_to "/ticket/#{params[:id]}/edit" and return
end
end
P.S.: You can use redirect_to and flash[:message] in one line:
redirect_to your_path(params), :notice => "your message"