I use PayPal-SDK-Rest gem. I have the next def inside of feed.rb(model):
def self.paypal_url(return_path)
values = {
business: "team#team.com",
cmd: "_xclick",
upload: 1,
return: "#{Rails.application.secrets.app_host}#{return_path}",
#invoice: id,
amount: 0.01,
item_name: "9dt9",
#item_number: course.id,
quantity: '1',
notify_url: "#{Rails.application.secrets.app_host}/hook"
}
#"#{Rails.application.secrets.paypal_host}/cgi-bin/webscr?" + values.to_query
"https://www.paypal.com/cgi-bin/webscr?" + values.to_query
end
Inside of view file I did put:
<%= link_to "Checkout", #feed.paypal_url("http://my_website.com/en") %>
For the notify_url I did use the next function in feed_controller:
def hook
params.permit! # Permit all Paypal input params
#status = params[:payment_status]
status = params[:st]
if status == "Completed"
Transaction.create(:status => params[:st], :transaction_id => params[:tx], :purchased_at => Time.now)
puts "Data: #{params[:st]} :: #{params[:tx]}"
else
puts "NothingHere"
end
render nothing: true
end
So, it must add my parameters to the table, but it doesn't. What is the problem, who knows? Why it doesn't insert anything into table?
Who can help me with it?
UPDATE
In the MGINX log I get:
Parameters: {"tx"=>"9BK361abcdefg473M", "st"=>"Completed", "amt"=>"0.01", "cc"=>"USD", "cm"=>"", "item_number"=>"", "locale"=>"en"}
Related
I have a Boolean field called :active and is changeable via Ajax. I have it working for unchecking the box, thereby making the boolean FALSE, or moreover, in the database it removes the attribute making it empty, but works nonetheless.
My problem is it does not work in reverse. I can check the box to make the boolean TRUE and it appears that it is doing something, but it does not actually make a change in the database.
The output in Webbrick shows it updated:
Processing by CompaniesController#toggle as JS
Parameters: {"Active"=>"228", "id"=>"228"}
SQL (0.5ms) UPDATE "companies" SET "active" = $1, "updated_at" = $2
WHERE "companies"."id" = $3 [["active", nil],
["updated_at", 2017-02-15 17:26:19 UTC], ["id", 228]]
(0.8ms) COMMIT
But the database didn’t update. I see where it says [[“active, nil] above, and that is the part that is not right. So technically the update is working, but I’m pretty sure my controller is why it is sending a nil on recheck.
So, how do I send a boolean TRUE in my controller, if that is indeed where I should do it.
companies_controller.rb
def toggle
#company = Company.find(params[:id])
if #company.update_attributes(active: params[:active])
# todo: maybe give a notice
else
# todo: maybe give a notice
end
end
index.html.rb
<%= check_box_tag 'Active', company.id, company.active,
data: {
remote: true,
url: url_for(action: :toggle, id: company.id),
method: "POST"
} %>
routes.rb
resources :companies do
resources :comments
member do
post 'toggle'
end
end
Edit
I got it to work by changing my controller to use an if statement. Not sure if this is the best approach, but it does work in both directions now.
companies_controller.rb
def toggle
#company = Company.find(params[:id])
if #company.active
#company.update_attributes(active: FALSE)
else
#company.update_attributes(active: TRUE)
end
end
You don't really need a separate route. Rather you can just send a PATCH request to your existing route:
<% form_for(#company) do |f| %>
<%= f.check_box :active, class: "company-toggle-active" %>
<% end %>
Make sure the controller handles JSON:
class CompaniesController < ApplicationController
# ...
def update
#company = Company.find(params[:id])
if #company.update(company_attributes)
respond_to do |f|
f.json { head :ok }
f.html { redirect_to #company }
end
else
respond_to do |f|
f.json { json: { errors: #company.errors }, status: 422 }
f.html { render :new }
end
end
end
private
def company_attributes
params.require(:company).permit(:foo, :bar, :active)
end
end
We can then setup an handler for the change event that updates with ajax:
$(document).on('change', '.company-toggle-active', function(){
$.ajax({
url: this.form.action,
type: 'PATCH',
dataType: 'json',
data: {
company: {
active: $(this).is(':checked') ? 'true' : 'false'
}
}
}).done(function(data, textStatus, jqXHR){
// do something if request is successful
}).fail(function(data, textStatus, jqXHR){
// do something if request fails
});
});
I am working on functionality whereby a table is displayed with records, each with radio buttons Reject and Approve. A user selects the appropriate radio button and presses process. Control is passed to process_campaigns. From here it breaks down the data and analyses each record's status. If it is approved it redirects to approve block and same with reject.
The following parameters are passed:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"9TCExvCmDahAWGQloPdaRkSowbBaxZGwZnRa8sbNkWM=", "campaign"=>{"2"=>{"start_date"=>"2016-07-18 15:43:00", "end_date"=>"2016-10-15 12:20:00", "merchant_revenue"=>"10", "status"=>"Approved", "notes"=>""}, "1"=>{"start_date"=>"2016-07-15 12:20:00", "end_date"=>"", "merchant_revenue"=>"10", "status"=>"Approved", "notes"=>""}}, "Commit"=>"Process"}
def process_campaign
authorize! :operator, current_user.operator
params[:campaign].each do |key, value|
if value[:status] == "Approved"
redirect_to approve_operator_campaign_path(key), :id => key, :start_date => value[:start_date], :revenue_mode => value[:revenue_model], :end_date => value[:end_date], :active => true, :status => 307 and return
elsif value[:status] == "Rejected"
redirect_to reject_operator_campaign_path(key), campaign_name: key, notes: value[:notes], :status => 307 and return
end
end
redirect_to operator_campaigns_path, flash: { notice: "Campaigns have been processed."}
end
def reject
authorize! :operator, current_user.operator
params[:campaign].each do |key, value|
if value[:status] = "Rejected"
#campaign = Campaign.active.where(id: key, operator_id: current_user.operator_id).last!
#campaign.data.merge!({:notes=>value[:notes]})
#campaign.status = "Rejected"
#campaign.save(validate: false)
end
end
end
def approve
#campaign = Campaign.find(params[:id])
params[:campaign].each do |key, value|
if value[:status] = "Approved"
#applied_campaign = AppliedCampaign.new(:campaign_id => key, :start_date => value[:start_date]||Time.now, :end_date => value[:end_date], :active => true)
end
end
end
The problem is when control is passed to approve or reject the entire campaign string is passed with both records contained within whereas I want to seperate each record and pass it individually. Can anyone indicate why the entire campaign string is being passed?
Move the params inside the route helper
redirect_to approve_operator_campaign_path(key, param_1: 1, param_2: 2)
# Parameters: { "id"=>"2" "param_1"=>"1", "param_2"=>"2" }
Change your method to:
def process_campaign
authorize! :operator, current_user.operator
params[:campaign].each do |key, value|
if value[:status] == "Approved"
redirect_to approve_operator_campaign_path(key, id: key, start_date: value[:start_date], revenue_mode: value[:revenue_model], end_date: value[:end_date], active: true, status: 307) and return
elsif value[:status] == "Rejected"
redirect_to reject_operator_campaign_path(key, campaign_name: key, notes: value[:notes], status: 307) and return
end
end
redirect_to operator_campaigns_path, flash: { notice: "Campaigns have been processed."}
end
I have the method below and I get the error
"no implicit conversion of String into Integer"
on line
if (!thisitem['value'].to_i.match(/[\/-].{2}/).nil?)
A Little background: I am new to this project, this is a internal CMS. I am attempting to upgrade from Rails 2 to Rails 4. I come from a ASP.NET background.
Parameters: Parameters: {"utf8"=>"✓",
"authenticity_token"=>"ahD3oriEXY895BNx53nd03Q6PQZ1yOQkgkpCGM4OlVqXODjrl3EIb6Uqa9mqVwwWgCQhV5qxRebCmEyoP57HzQ==",
"info_items"=>{"1"=>{"id"=>"1", "description"=>"Billing Rate",
"value"=>"110"}, "2"=>{"id"=>"2", "description"=>"Travel Rate",
"value"=>"55"}}, "commit"=>"Update"}
def update_info
#updated_items=params[:info_items]
#updated_items.each do |thisitem|
#item=TrackInformation.find_by_id(thisitem)
if (!thisitem['value'].match(/[\/-].{2}/).nil?)
thisdate=thisitem['value']
if !thisdate.match(/\/.{2}/).nil?
newdate=Date.strptime(thisdate,"%m/%d/%Y")
else
newdate=Date.strptime(thisdate,"%m-%d-%Y")
end
thisdate=newdate
thisitem['value']=thisdate
end
#item.update_attributes(thisitem)
#item.changed_by=User.find(session[:user]).id
#item.save
end
end
edit:
so reading #Anand I realized that a date should not equal value because value is a dollar amount, so I modified the method to be:
def update_info
i = 1
#updated_items=params[:info_items]
#updated_items.each do |this_item|
#item=TrackInformation.find_by_id(this_item[i][:id])
#item.description = this_item[i][:description]
#item.value = this_item[i][:value]
#item.changed_by=session[:user].to_i
#item.save
i = i + 1
end
redirect_to :controller => 'admin', :action => 'list'
end
Now I get:
undefined method `[]' for nil:NilClass
Edit 2:
def update_info
byebug
#updated_items=params[:info_items]
#updated_items.each do |id, description, value|
#item=TrackInformation.find_by_id(id)
#item.value = value
#item.description = description
#item.changed_by=session[:user]
#item.save
end
redirect_to :controller => 'admin', :action => 'list'
end
this seems to work but puts this in the DB:
Edit 3:
def update_info
#updated_items=params[:info_items]
#updated_items.each do |this_item_key,this_item_value|
#item=TrackInformation.find_by_id(this_item_key)
#item.update_attribute(this_item_key, this_item_value)
#item.changed_by=session[:user]
#item.save
end
redirect_to :action => 'list'
end
Based on your params, each thisitem is a hash - you can get the key and value as block params, and use them appropriately. Also, if !(something).nil? can be simplified to if something.present?. Finally, it is a good idea to name variables with underscore - this_item instead of thisitem
Update: As the question has changed, updated the code below as well
def update_info
#updated_items=params[:info_items]
#updated_items.each do |this_item_key,this_item_value|
#item=TrackInformation.find_by_id(this_item_key)
#item.value = this_item_value['value']
#item.description = this_item_value['description']
#item.changed_by=session[:user]
#item.save
end
end
I have a table 'Likes' with columns business_id, user_id and liked(0,1) and a function 'change_like_status'.
Now on every function call, If the value is 1 then set it to 0 (or vice versa) and if record doesn't exists then create one with value 1.
The first_or_create method is working just fine but how can i toggle value of column 'liked' while using this method?
Here is my function:
def change_like_status
if current_user.present?
status = Like.where("business_id = ? AND user_id = ?",params['id'],current_user.id).first_or_create(:business_id => params['id'],:user_id => current_user.id,:liked => '1')
abort status.inspect
else
return render :json => {:status => false,:msg=>"You need to sign in before performing this action."}
end
end
In you controller, make the changes
def change_like_status
if current_user
status = Like.create_or_change_status(params[:id], current_user.id)
else
return render json: { status: false, msg: "You need to sign in before performing this action." }
end
end
In your model like.rb file, add a method
def self.create_or_change_status(business_id, user_id)
status = where(business_id: business_id, user_id: user_id).first
if status.nil?
status = create({business_id: business_id, user_id: user_id, liked: 1})
else
status.update_attributes(liked: !status.liked)
end
status
end
def change_like_status
if current_user
current_user.likes.find_by(business_id: params[:id]).switch_status!
else
return render json: { status: false, msg: "You need to sign in before performing this action." }
end
end
class Like
def switch_status!
self.update_column :liked, !liked
end
end
other approach should be something like that
class Like
def switch_status!
self.update_column :liked, !liked
end
end
class User
def likes id
likes_for_business id
end
def likes_for_business(id)
likes.find_by(business_id: id) || likes.create(:business_id: id, liked: true)
end
end
# controller
current_user.likes(params[:id]).switch_status!
Im using jquery-tokeninput, but a fork of it which allows the User to add new custom tokens (Tag) for each Resource.
Example here (Scroll down to the tag box and type a few letters. you can type ones that dont exist): http://www.tomsguide.fr/solutions/nouveau_sujet.htm
The current return value from the fork I'm using is this (new value in quotes):
16,42,'Subway',37,'McDonald\'s',734
I'm having extreme difficulty trying to handle this in Rails. This sums it up perfectly.
This is what I have so far, and its not working, probably for a lot of reasons I'm not seeing, but the main reason is that I need to create new Tag instances but not save them, that way I can somehow pass them back into the token input, and save the new Tags along with the new Resource when they submit the form. When you use Tag.new though, it doesnt create an ID.
resource.rb
attr_accessor :tokens_list
# CUSTOM TOKENS
def tag_tokens=(tokens)
self.tokens_list = tokens.split(",")
if new_custom_tokens?
self.tokens_list.each do |token|
tokens_list << token if token.include? "'"
end
end
self.tag_ids = self.tokens_list
end
def new_custom_tokens?
self.tokens_list.each do |token|
return true if token.include? "'"
end
false
end
resources_controller.rb
def create
#title = "Submit Resource"
#resource = Resource.new(params[:resource])
assign_to_global_user?
# CUSTOM TOKENS
if #resource.new_custom_tokens?
custom_token_time_restriction
# Create Tag.new
end
if #resource.valid?
#resource.save
flash[:notice] = "Your link has been successfully submitted."
redirect_to root_url
else
render :action => :new
end
end
def assign_to_global_user?
if user_signed_in?
#resource.user_id = current_user.id
else
#resource.user_id = User.find_by_username("Global_User").id
end
end
private
# CUSTOM TOKENS
def custom_token_time_restriction
limit = 7 # days
if (#resource.user_id != User.global_user_id) and (Time.now - limit.days > User.find(#resource.user_id).created_at)
# TODO: Check if they are anonymous or their account is newer than 7 days
else
flash[:notice] = "You be Logged in to add new tags, and your account must be older than #{limit} days."
render :action => :new
end
end
new.html.erb (for resource#new)
<div class="field">
<%= f.label :tags %>
<%= f.text_field :tag_tokens, "data-pre" => #resource.tags.to_json(:only => [:id, :name]), :class => :tagbox %>
</div>
I had the same problem. This is what I have done:
This is the function where I return tokens of search in json format.
tags = TagMaster.where("name LIKE ?", "%#{params[:q]}%").limit(10)
if tags == []
list << {"id" => "0","name"=>new_tag.rstrip}
else
tags.each { |tag| list << {"id" => tag.id.to_s, "name" => tag.name }}
end
respond_to do |format|
format.json { render :json => list.to_json, :layout => false }
end
Now this will allow show you whatever you type in auto complete dropdown and on clicked it will show as a token.
Now you can't add any more custom tokens because any token that is not in database will return id 0 so only one custom token is allowed at this point of time.
For that problem I did following.
var k = jQuery.noConflict();
k("#project_tags").tokenInput("tag_list", {
hintText: "Enter Tags for your Project",
noResultsText: "No Such Tags",
searchingText: "Looking for your Tags",
preventDuplicates: true,
theme: "facebook",
onAdd: function (item) {
if (item.id == '0') {
k.ajax({
url: '/add_project_tag',
data: { name: item.name },
success:function(data) {
k("#project_tags").tokenInput("add", {id: data, name: item.name});
k("#project_tags").tokenInput("remove", {id: '0' });
}
});
}
}
});
As you can see here i call add_project_tag where I store that custom tag into database and it returns id of that inserted tag. So now you simply add the same token with it's id and remove token with 0.
So now there won't be any token with 0 and you can add as many new token as you want.
Hope this helps. Throw your questions if any more complications.