on Update, if one of my param is blank, how to delete it from database? - mysql

I not sure how to delete a param in database, when updating and the param is left blank. Below is my current code-
def update
if !ABC.exists?(:id =>params[:id])
render json: { errors: #error }, status: 500
else
#abc = ABC.find(params[:id])
if #abc.update(permitted_update_abc_params)
render json: #abc, status: 200
else
render json: #abc.errors.full_messages, status: 500
end
end
end

You can simply run
obj.update_attributes(:field_name => params[:present_params], :field_name => params[:present_params], :field_name => params[:blank_params])
this blank param will replace database field value with existing blank value.

Related

undefined method `bytesize' for {"COUNT(*)"=>0}:Hash

An error is displayed for the client when it is not banned which is:
undefined method `bytesize' for {"COUNT(*)"=>0}:Hash
I use the mysql2 lib
post '/mario/login' do
credentials = CGI.parse request.body.read
if !credentials.has_key?('username') || !credentials.has_key?('password')
status 603
return "MISSING_FIELD"
end
results = bans.execute request.ip
results.each do |row|
if row['COUNT(*)'] > 0
status 603
return "BANNED"
end
puts "ok"
end
end
Your code is trying to return the hash results after the function ends. Return with a proper response code/type and it should work.
Last line/block in Ruby is returned in any function. In your case, last block is results.each which returns back results which is not a valid response type for sinatra.

Print a value of a key from json

I am trying to parse a json file and extract the value of a key from it, and pass it to another post request. However, I am not able to extract they value, when I try, it prints the key itself instead of value
PFB the json file
{
"data":{
"isActivated":true,
"userDetails":{
"userId":"52321713-add8-4455-9e0c-426eab923338",
"oktaId":"00ub24c5bs6awQyBD0h7",
"contactId":"7234294092390",
"oktaSessionToken":"20111UqAZ9-E1YPlNcXBLRCu_ZHHzBCH2q_j01yiIkPyRp5-0E7HAQQ",
"oktaSessionId":"102a9q79TrqRWek9vHEPkP3yQ",
"apiToken":"f5c95fd8-efc4-497e-8128-51a014de3a9a",
"firstName":"Judy",
"lastName":"Test1",
"middleName":null,
"email":"abc#mailinator.com",
"isEmployee":true,
"pushNotificationStatus":true
},
"companyDetails":{
"profileScreenBackgroundColor":"13253D",
"companyColor":"7ED321",
"companyName":"Mobile App Demo",
"companyLogo":"http://",
"isSSO":false
}
}
}
PFB the hash file:
{"data"=>{"isActivated"=>true, "userDetails"=>
{"userId"=>"52321713-add8-4455-9e0c-426eab923338",
"oktaId"=>"00ub24c5bs6awQyBD0h7", "contactId"=>"0033300001tZ8k5AAC",
"oktaSessionToken"=>"201112Ncbw364pHojkD4UlzGb1knz9UTZPIy2LFDn9Tgy_FmgEpZmmU",
"oktaSessionId"=>"102Kd-c2yEeSnmwr3YKX8qeyg",
"apiToken"=>"f8f070e2-e51b-4d69-8b1a-b7b63d25e781",
"firstName"=>"Judy", "lastName"=>"Test1",
"middleName"=>nil,
"email"=>"judy.test1#mailinator.com",
"isEmployee"=>true,
"pushNotificationStatus"=>true},
"companyDetails"=>{"profileScreenBackgroundColor"=>"13253D", "companyColor"=>"7ED321",
"companyName"=>"Mobile App Demo", "companyLogo"=>"https:",
"isSSO"=>false}}}
The code below:
I had tried almost all means, not sure what am i missing.
apitoken = RestClient.post("https://", {'email'=>arg,'password'=>'abcs','deviceUUId'=>'udid', 'deviceTypeId'=>1}.to_json, { "Content-Type" => 'application/json','buildNumber' => '000','deviceTypeId'=>'9'})
puts apitoken
puts "**************"
puts apitoken["apiToken"]
logindetails = JSON.parse(apitoken)
tada = JSON.parse(logindetails)['data']['apitoken']
puts tada
puts logindetails
result = logindetails["data"]["apiToken"]
puts result
puts "**************"
logindetails.each do |logindetail|
puts logindetail
puts logindetail["apiToken]
puts "**************"
end
result = logindetails['apiToken']
puts result
end
The output I get is apiToken instead of the value of it. Any help is greatly appreciated.
The token is under data userDetails apiToken:
json['data']['userDetails']['apiToken'] #=> f5c95fd8-efc4-497e-8128-51a014de3a9a

Ruby: calling method within another method's conditional statement

I'm trying to call the method print_json within a conditional statement that is contained in another method named list_trends. I did this becauese my code was starting to look too nested. However I get an error when I run that says:
syntax error, unexpected tSTRING_BEG, expecting keyword_do or '{' or '('
...i_key]) ? print_trends : puts "Invalid API Key, operation ab...
Here is my code:
#!/usr/bin/ruby
require 'thor'
require 'json'
class ListTrends < Thor
desc "list trends", "list out trends from JSON file"
option :api_key, :aliases => "--api-key", :type => :string, :required => true
def print_json
json = File.read('trends_available.json')
trends_hash = JSON.parse(json)
trends_hash.each do |key|
key.each do |k,v|
puts "Trend #{k}: #{v}"
end
puts ""
end
end
def list_trends
re = /^(?=.*[a-zA-Z])(?=.*[0-9]).{8,}$/
if options[:api_key]
if re.match(options[:api_key]) ? print_json : puts "Invalid API Key, operation abort..."
end
end
end
ListTrends.start(ARGV)
This
if options[:api_key]
if re.match(options[:api_key]) ? print_json : puts "Invalid API Key, operation abort..."
end
Should just be
if options[:api_key]
re.match(options[:api_key]) ? print_json : puts "Invalid API Key, operation abort..."
end
Though I would prefer:
if options[:api_key]
if re.match(options[:api_key])
print_json
else
puts "Invalid API Key, operation abort..."
end
end
Or if you must put it on one line:
if options[:api_key]
if re.match(options[:api_key]) then print_json else puts "Invalid API Key, operation abort..." end
end

Insert json data to existing remote server in corona

How to post data to my own server. I can fetch data from it but can't add data .Code for fetch is below:
local function networkListener( event )
if ( event.isError ) then
print( "Network error!")
else
local json=event.response
local length=string.len(json)
json=string.sub(json, 50, (length-1));
jsonTable=JSON.encode(json)
local t = jsonTable
print(jsonTable)
-- Go through the array in a loop
for key in pairs(t) do
-- Here you can do whatever you like with the values
print(t[key]["AuthorID"])
print(t[key]["AuthorName"])
--print(t[key]["returnvalue3"])
end
end
end
local remoteFeed="http://www.xtremeesolutions.com/xesapps/webservice/readauthors.php"
network.request(remoteFeed, "GET", networkListener)
--And trying code to post data is
local function postData(e)
if (e.isError)then
print("Error ");
else
print("Error ".. e.response);
end
end
local params = {
body = query
}
network.request(remoteFeed, "POST",postData,params))
Above code not giving any error but also not inserting values.Please suggest me to solve this.
I think you should use "POST" instead of "GET", see the code below:
...
local remoteFeed="http://www.xtremeesolutions.com/xesapps/webservice/readauthors.php"
network.request(remoteFeed, "POST", networkListener, params)
Maybe you should also check this link http://docs.coronalabs.com/api/library/network/request.html at section: HTTP POST with custom headers
EDITED
the loop for handle post value should be:
if ( event.isError ) then
print( "Network error!")
else
...
for key in pairs(t) do
postData = t[key]["AuthorID"] .. "=" .. t[key]["AuthorName"]
end
local params = {}
params.body = postData
local remoteFeed="http://www.xtremeesolutions.com/xesapps/webservice/readauthors.php"
network.request(remoteFeed, "POST", networkListener, params)
end
those lines should be togather in else scope.

Delayed Indexing in SunSpot solr still make Delete request on record save

The delayed indexing is working fine but on record save it sends some delete request to websolr... here in the log it shows
SOLR Request (14.3ms) [ path=# parameters={data: Message 547488, headers: {"Content-Type"=>"text/xml"}, method: post, params: {:wt=>:ruby}, query: wt=ruby, path: update, uri: http://index.websolr.com/solr/index/update?wt=ruby, open_timeout: , read_timeout: } ]
SOLR Request (12.4ms) [ path=# parameters={data: Message 547488, headers: {"Content-Type"=>"text/xml"}, method: post, params: {:wt=>:ruby}, query: wt=ruby, path: update, uri: http://index.websolr.com/solr/index/update?wt=ruby, open_timeout: , read_timeout: } ]
SOLR Request (9.7ms) [ path=# parameters={data: , headers: {"Content-Type"=>"text/xml"}, method: post, params: {:wt=>:ruby}, query: wt=ruby, path: update, uri: http://index.websolr.com/solr/index/update?wt=ruby, open_timeout: , read_timeout: } ]
These are the 3 requests that has been made against single message creation.
here is my search block
searchable :if => proc { |message| !message.user_messages.blank? } do
text :message_body do
CGI.escape(self.body || "")
end
text :subject do
CGI.escape(self.subject || "")
end
text :sender_name do
user.blank? ? "" : user.full_name
end
integer :users_ids, :multiple => true do
user_messages.map{|um| um.user_id}
end
time :created_at
end handle_asynchronously :solr_index
Please look in it asap,
thanks
To queue Sunspot deletes with DelayedJob, you should also add this line:
handle_asynchronously :remove_from_index