API received information from calls is appended with extra characters - ruby-on-rails

I have a controller for my API for Rails app.However, messages received are appended with 6 underscores. #message.message = CGI.unescape(params[:message]).strip has the #message.message string appended with an extra 6 underscores.
For example;
#message.message for xample ends up with the value "Hi, Joseph and Beatrice invite you for our wedding day preparation meetings Fridays, starting 5/10/2012 at Calvary Chapel Kampala - William Street Gadith ______"
The controller is as shown below;
def sms
#message = Message.new
decoded_to = CGI.unescape(params[:to])
##message.to = decoded_to.gsub(/[^\d]/,"")
#message.to = CGI.unescape(params[:to]).strip.gsub("+","").gsub(/\s+/, "")
#message.from = CGI.unescape(params[:from])
#message.message = CGI.unescape(params[:message]).strip
#message.user_id = current_user.id
#message.status = 'Queued'
if #message.save
MessageWorker.perform_async(#message.id, [""], current_user.id)
render json: {status: "Success"}
else
render json: {status: "Failed" }
end
end
What could be the problem?
All help is appreciated.

Related

Rails 5: Add loop to create method and increment by 1 each time

I want to add an order_number to my reservations. Now everytime an order gets created I want to change the value of the order_number.
I tried #reservation.order_number = 1000 and then #reservation.order_number += 1, but I soon realised that this doesn't make any sense.
Here is my create method from my reservations controller:
def create
service = Service.find(params[:service_id])
if current_user.admin?
flash[:alert] = "Du kannst nicht dein eigenes Angebot kaufen"
elsif current_user.stripe_id.blank?
flash[:alert] = "Füge eine Zahlungsmehtode hinzu"
return redirect_to payment_method_path
else
#reservation = current_user.reservations.build
#reservation.service = service
#reservation.price = service.price
#reservation.order_number = 1000
if #reservation.Bearbeitung!
flash[:notice] = "Ihre Anfrage wurde erfolgreich versendet"
ReservationMailer.confirm_email_to_guest(#reservation.user, service).deliver
confirm_sms(service, #reservation)
else
charge(service, #reservation)
end
end
redirect_to submit_reservation_path(#reservation)
end
in your model you can do something like,
before_save :add_order_number
private
def add_order_number
default_order_number = 1000
previous_order = Order.last
if previous_order
puts "last order_number was #{previous_order.order_number}"
self.order_number = previous_order.order_number + 1
else
puts "there was no last number, setting order number to default_order_number"
self.order_number = default_order_number
end
end

How can I update serialized data in a Rails/MariaDB backend?

Currently, I have some QueuedImages that become GalleryImages once certain conditions are met.
#image = GalleryImage.new(image_params.except(:tags))
#image.user = current_user
#queued = QueuedImage.new(user: current_user)
#queued.image = #image
Before saving this method, transform the images into JSON:
def image_to_json
self.image_data = #image.to_json(include: :plain_images)
end
I'm trying to update the serialized hash/JSON like this:
def update
#queued = QueuedImage.find(params[:id])
hash_as_string = #queued.image_data
i_data = JSON.parse(hash_as_string.gsub('=>', ':'))
i_data["title"] = params["title"]
i_data["description"] = params["description"]
i_data["folder_id"] = params["folder_id"]
i_data["nsfw"] = params["nsfw"]
i_data["tags"] = params["tags"]
#queued.image_data = i_data
if #queued.save
render json: #queued, scope: current_user
else
render json: #queued.errors.as_json(full_messages: true), scope: current_user, status: :unprocessable_entity
end
end
Which throws me a parse error, what am I doing wrong?
How can I properly update the serialized string?
The thing is that when it transforms from a QueuedImage to a GalleryImage, another method takes that data and evaluates it and creates the new GalleryImage, so it has to be in the exact format, and I believe what I'm doing in the update method is wrong, even though I save it as a string in the DB.

Improving ruby code

people said to me that I have an wrong code at this point. The main idea of this method is to create 1 event if user pressed once, and a row of events if user pressed daily or weekly. Everything works well, but code is so bulky.
def create
#event = Event.new(event_params
#event.start_time = DateTime.parse(params[:start_time], "%Y-%m-%d %H:%i")
#event.end_time = DateTime.parse(params[:end_time], "%Y-%m-%d %H:%i")
#event.user_id = current_user.id
#event.update_attributes(:repeat_id => #event.id) if #event.save
respond_to do |format|
if #event.save
format.html { redirect_to persons_profile_path }
else
format.html { render :new }
format.json { render json: #event.errors, status: :unprocessable_entity }
end
interval = 60 if #event.repeat =='daily'
interval = 20 if #event.repeat =='weekly'
#creating row of events
if #event.repeat != 'once'
(1..interval).each do |i|
#event = Event.new(event_params)
#event.start_time = DateTime.parse(params[:start_time], "%Y-%m-%d %H:%i")
#event.end_time = DateTime.parse(params[:end_time], "%Y-%m-%d %H:%i")
#event.user_id = current_user.id
if #event.repeat =='daily'
#event.start_time = DateTime.parse(#event.start_time.to_s) + i.day
#event.end_time = DateTime.parse(#event.end_time.to_s) + i.day
end
if #event.repeat =='weekly'
#event.start_time = DateTime.parse(#event.start_time.to_s) + i.week
#event.end_time = DateTime.parse(#event.end_time.to_s) + i.week
end
#event.update_attributes(:repeat_id => k) if #event.save
#event.save
end
end
I can't find another solutions. Any ideas? Dont pay attention on parse methods on date, its needed to JS.
I think the issue is that you are using the controllers to do too much work and it's hard to read. Typically controllers look like:
def create
#client = Client.new(params[:client])
if #client.save
redirect_to #client
else
render "new"
end
end
Take a moment and think about your data. You create events. You want your events to appear in a row if the create button is pressed daily or weekly. So we are thinking about how to display it, that's a css/html issue, not something relating to controllers.
The reason people are saying your code as wrong is because you are doing something very atypical. If you submitted this code for school or a project you would get a low score because you are making everyone else work hard to understand your work, instead of following the same basic style that everyone was trained in.

Rails how to return single JSON object instead of array of JSON objects?

I am limiting to 1, so I thought it would simple return an object in this case the same as .find_by_email
Code:
# GET /users/:identified/type/:social_type
# Returns a single record - so limit 1
def find
#user = User.where("identified = ? AND social_type = ?", params[:identified], params[:social_type]).limit(1)
if not #user.empty?
render json: #user.as_json, status: :created
else
render json: #user, status: :not_found
end
end
Current Response:
[{"id":7,"voy_num":null,"voy_pin":null}]
How can ensure I return a single JSON object?
To get the single object, use first with where like this:
#user = User.where("identified = ? AND social_type = ?", params[:identified], params[:social_type]).first

rails redirect after create problem

Could anyone help with this problem:
Upon "create", the user is redirected to the url: model/model_id (eg post/1), instead I am redirected to models/url_encoding_object (eg posts/.%23) and there is an "406 Not Acceptable" message in the console.
Typically, upon create, the console's message is "Processing PostsController#create (for 000.0.0.0 at 2009-11-23 12:32:52) [POST]", but with this error, the message is "Processing PostsController#create to # (for 000.0.0.0 at 2009-11-23 12:32:52) [POST]"
I've seen austinfromboston's response and tried his "old fashioned but effective" solution to that similar problem, but it doesn't work for me.
Any help would be greatly appreciated
Controller Code:
# POST /groups
# POST /groups.xml
def create
#group = Group.new(params[:group])
#group.category = params[:category]
#group.user = current_user
#here we add the current user to the membership collection of the group
#membership = #group.memberships.build(params[:membership])
#membership.group = #group
#membership.user = current_user
#membership.initiator = false
#membership.membership_status_id = 2
#and here we set the current_user as the owner of the group
#group_permission = #group.group_permissions.build(params[:group_permission])
#group_permission.membership = #membership
#group_permission.group_role = GroupRole.find_by_name('Owner')
unless params[:metro_area_id].blank?
#group.metro_area = MetroArea.find(params[:metro_area_id])
#group.state = (#group.metro_area && #group.metro_area.state) ?
#group.metro_area.state : nil
#group.country = #group.metro_area.country if (#group.metro_area &&
#group.metro_area.country)
else
#group.metro_area = #group.state = #group.country = nil
end
#group.tag_list = params[:tag_list] || ''
# unless #user.is_in_group?(#group)
# #user.memberships << #group
# end
respond_to do |format|
if #group.save
flash[:notice] = :group_was_successfully_created.l
format.html { redirect_to(group_path(#group.id)) }
else
format.html {
#metro_areas, #states = setup_metro_area_choices_for(#group)
if params[:metro_area_id]
#metro_area_id = params[:metro_area_id].to_i
#state_id = params[:state_id].to_i
#country_id = params[:country_id].to_i
end
render :action => "new"
}
end
end
end
Looks like either your routes are off somewhere or your model_id parameter is not what you are expecting. Might want to check to see what that parameter is being set to.
It's also really hard to give any suggestions without seeing controller code. Can you post the method making this call?
There's a lot of superfluous code, in your controller. It still works, but you're doing a lot of things the hard way.
Your problem is this line:
format.html { redirect_to(groups_path(#group.id)) }
Which redirects to the collective groups url adding the parameter #group.id.
What it should be is
format.html { redirect_to(group_path(#group.id)) }
# POST /groups
# POST /groups.xml
def create
#group = Group.new(params[:group])
#group.category = params[:category]
#group.user = current_user
#here we add the current user to the membership collection of the group
#membership = #group.memberships.build(params[:membership])
#membership.group = #group
#membership.user = current_user
#membership.initiator = false
#membership.membership_status_id = 2
#and here we set the current_user as the owner of the group
#group_permission = #group.group_permissions.build(params[:group_permission])
#group_permission.membership = #membership
#group_permission.group_role = GroupRole.find_by_name('Owner')
unless params[:metro_area_id].blank?
#group.metro_area = MetroArea.find(params[:metro_area_id])
#group.state = (#group.metro_area && #group.metro_area.state) ? #group.metro_area.state : nil
#group.country = #group.metro_area.country if (#group.metro_area && #group.metro_area.country)
else
#group.metro_area = #group.state = #group.country = nil
end
#group.tag_list = params[:tag_list] || ''
unless #user.is_in_group?(#group)
#user.memberships << #group
end
respond_to do |format|
if #group.save
flash[:notice] = :group_was_successfully_created.l
format.html { redirect_to(groups_path(#group.id)) }
else
format.html {
#metro_areas, #states = setup_metro_area_choices_for(#group)
if params[:metro_area_id]
#metro_area_id = params[:metro_area_id].to_i
#state_id = params[:state_id].to_i
#country_id = params[:country_id].to_i
end
render :action => "new"
}
end
end
end
What is this .1 doing at the end of the line??
flash[:notice] = :group_was_successfully_created.l
I tried to run similar code in my environment and it choked on that.
It should also reference:
group_path(id)
not
groups_path(id)

Resources