Repacking query result from multiple models. Rails-way - ruby-on-rails

I have a controller that renders json. Here's code:
class AppLaunchDataController < ApiController
def index
service_types = []
vendors = []
tariffs = []
fields = []
vendors_hash = {}
service_types_hash = {}
tariffs_hash = {}
fields_hash = {}
#service_types = ServiceType.select("title, id").all.each do |service_type|
service_types_hash = {id: service_type.id, title: service_type.title}
service_types << service_types_hash
#vendors = service_type.vendors.select("title, id").all.each do |vendor|
vendors_hash = {id: vendor.id, title: vendor.title}
vendors << vendors_hash
#tariff = vendor.tariffs.select("title, id").all.each do |tariff|
tariffs_hash = {id: tariff.id, title: tariff.title}
tariffs << tariffs_hash
#fields = tariff.fields.select("id, current_value, value_list").all.each do |field|
fields_hash = {id: field.id, current_value: field.current_value, value_list: field.value_list}
fields << fields_hash
end
tariffs_hash[:fields] = fields
fields = []
end
vendors_hash[:tariffs] = tariffs
tariffs = []
end
service_types_hash[:vendors] = vendors
vendors = []
end
render json: service_types
end
end
Return value looks like this:
[{"id":1,"title":"Water",
"vendors":[{"id":1,"title":"Vendor_1",
"tariffs":[{"id":1,"title":"Unlim",
"fields":[{"id":1,"current_value":"200","value_list":null},{"id":2,"current_value":"Value_1","value_list":"Value_1, Value_2, Value_3"}]},{"id":2,"title":"Volume",
"fields":[]}]},
{"id":2,"title":"Vendor_2",
"tariffs":[]}]},
{"id":2,"title":"Gas",
"vendors":[]},
{"id":3,"title":"Internet",
"vendors":[]}]
It works, but I'm sure there's another (more rails-) way to get the result.
If anyone dealt with it before, please help. Thanks.

just use
# for eager-loading :
#service_types = ServiceType.includes( vendors: {tariffs: :fields} )
# now for the json :
#service_types.to_json( include: {vendors: {include: {tariffs: { include: :fields}}}} )
if your ServiceType object will always have this kind of representation, just override the model's as_json method:
class ServiceType
def as_json( options={} )
super( {include: :vendors }.merge(options) ) # vendors, etc.
end
end
this is encouraged way to do it in rails : calling to_json on the model will just call as_json, possibly with additional options. In fact, as_json describes the canonical json representation for this model. See the api dock on to_json for more insight.
If your needs are more peculiar ( as using selects for a faster query ), you can always roll your own to_json_for_app_launch_data method on the model (using or not as_json), or even better on a presenter

Related

Ruby: adding multiple rows to a hash key

I've got a class that looks like this:
class VariableStack
def initialize(document)
#document = document
end
def to_array
#document.template.stacks.each { |stack| stack_hash stack }
end
private
def stack_hash(stack)
stack_hash = {}
stack_hash['stack_name'] = stack.name
stack_hash['boxes'] = [stack.boxes.each { |box| box_hash box }]
stack_hash
end
def box_hash(box)
box_hash = {}
content = []
box.template_variables.indexed.each { |var| content << content_array(var) }
content.delete_if(&:blank?)
box_hash.store('content', content.join("\n"))
return if box_hash['content'].empty?
box_hash
end
def content_array(var)
v = #document.template_variables.where(master_id: var.id).first
return unless v
if v.text.present?
v.format_text
elsif v.photo_id.present?
v.image.uploaded_image.url
end
end
end
The document I'm testing with has two template_variables so the desired result should be a nested hash like so:
Instead I'm getting this result:
=> [#<Stack id: 1, name: "User information">]
i.e., I'm not getting the boxes key nor it's nested content. Why isn't my method looping through the box_hash and content fields?
That's because the to_array method uses each method, which returns the object it's been called on (in this case #document.template.stacks)
Change it to the map and you may get the desired result:
def to_array
#document.template.stacks.map { |stack| stack_hash stack }
end

Trigger rails controller function - Paypal Website Standard IPN

I've got a Paypal IPN that comes into a PaymentNotificationsController in my app. However, some variables depend on the number of items in a cart, so i want to extract them before creating the PaymentNotification.
So far, i've got:
class PaymentNotificationsController < ApplicationController
protect_from_forgery except: [:create]
def create
PaymentNotification.create!(params: params,
item_number: params[:item_number], item_name: params[:item_name], quantity: params[:quantity]
render nothing: true
end
end
However, when the notification comes from PayPal, it comes in the form of item_name1, item_number1, quantity1, item_name2, item_number2, quantity2 and so on.
Even if its just one item, it would come as item_name1, item_number1, quantity1, option1 and so on.
I have this function to try and extract the variables, but i don't know how to trigger the function. I tried using a before_action at the top of the controller but it didn't work. Returned wrong number of arguments(0 for 1):
ITEM_PARAM_PREFIXES = ["item_name", "item_number", "quantity"]
def extract_ipn_items_params(params)
item_params = []
loop do
item_num_to_test = item_params.length + 1
item_num_suffix = item_num_to_test.to_s
possible_param_name = ITEM_PARAM_PREFIXES[0] + item_num_suffix
if params.include?(possible_param_name)
this_item_params = {}
ITEM_PARAM_PREFIXES.each do |prefix|
this_item_params[prefix] = params[prefix + item_num_suffix]
end
item_params.push this_item_params
else
return item_params
end
end
end
So i'm asking, how do i trigger the function to extract the variables and put them into params[:item_number], params[:item_name], params[:quantity] for each item in the cart so if there are two items, two separate PaymentNotifications would be created?
Note: Both methods are in the same PaymentNotificationsController.
Any help would be appreciated. Thanks in advance!
I assume your method extract_ipn_items_params already fetches the data you require, you can remove the params argument to the method, as the params is always available in the actions/methods of the controller.
ITEM_PARAM_PREFIXES = ["item_name", "item_number", "quantity"]
def extract_ipn_items_params
mod_params = Hash.new{|k, v| k[v] = {} }
ITEM_PARAM_PREFIXES.each do |item_data_key|
key_tracker = 1
loop do
current_key = (item_data_key + key_tracker.to_s).to_sym
if params.include? current_key
mod_params[key_tracker][item_data_key] = params[current_key]
else
break
end
key_tracker += 1
end
end
mod_params
end
The method returns a hash of hashes like:
{1 => {item_name: 'Item 1', item_number: 1084, quantity: 15}}, if you have nested attributes set up for a user, I think you should be able to do something like, not really sure, but should be possible:
user.update(payment_notifications_attributes: extract_ipn_items_params)
Let me know if that works for you.
UPDATE
Based on the Github Gist, here's something I was able to come up with:
class PaymentNotificationsController < ApplicationController
protect_from_forgery except: [:create]
ITEM_PARAM_PREFIXES = ["item_name", "item_number", "quantity", "option_name"]
def create
extract_ipn_items_params.each do |key, values|
# this approach loops through all the returned results, nested attributes may help abstract this though
PaymentNotification.create(values)
render nothing: true
end
def details
# params.extract_ipn_items_params #this doesn't exist as params is an instance of ActionController::Parameters
PaymentNotification.update_attributes(line_item_id: params[:item_number], product_title: params[:item_name], option_name: params[:option_name], quantity: params[:quantity])
end
private
def additional_attributes
# create this for additional merge attributes. A better place for these would be the parent of this
{
params: params,
cart_id: params[:invoice],
status: params[:payment_status],
transaction_id: params[:txn_id],
first_name: params[:first_name],
last_name: params[:last_name],
email: params[:payer_email],
address_name: params[:address_name],
address_street: params[:address_street],
address_city: params[:address_city],
address_state: params[:address_state],
address_zip: params[:address_zip],
address_country: params[:address_country]
}
end
def extract_ipn_items_params
mod_params = Hash.new{|k, v| k[v] = {}.merge(additional_attributes) }
ITEM_PARAM_PREFIXES.each do |item_data_key|
key_tracker = 1
loop do
current_key = (item_data_key + key_tracker.to_s).to_sym
if params.include? current_key
mod_params[key_tracker][item_data_key] = params[current_key]
else
break
end
key_tracker += 1
end
end
mod_params
end
end
Let me know if that fixes your problem.
You should have payment_id so you can find it by using gem 'paypal-sdk-rest'
payment = PayPal::SDK::REST::Payment.find payment_id
then you could see all details in payment object

Create or Update Rails 4 - updates but also creates (Refactoring)

In my Rails API I have the following code in my Child model:
before_create :delete_error_from_values, :check_errors, :update_child_if_exists
def delete_error_from_values
#new_error = self.values["error"]
#values = self.values.tap { |hs| hs.delete("error") }
end
def update_child_if_exists
conditions = {type: self.type, parent_id: self.parent_id}
if existing_child = Child.find_by(conditions)
new_values = existing_child.values.reverse_merge!(#values)
hash = {:values => new_values}
existing_child.update_attributes(hash)
end
end
def check_errors
if self.type == "error"
conditions = {type: self.type, parent_id: self.parent_id}
if existing_child = Child.find_by(conditions)
bd_errors = existing_child.error_summary
bd_errors[#new_error] = bd_errors[#new_error].to_i + 1
hash = {:error_summary => bd_errors}
existing_child.update_attributes(hash)
else
self.error_summary = {#new_error => 1}
end
end
end
This works like expected, except for one small detail: The Child is updated if a record by type and parent_id already exists, but it is also created. How can I refactor this to stop creation?
I've tried to include return false, but if I do this, the update is not successful.
I wish to have something like find_or_create_by, but I'm not sure how to use it for this cases.
May be you can refactor your code in following approach:
def create
#parent = Parent.find(params[:parent_id])
existing_child = Child.where(type: child_params[:type], parent_id:
child_params[:parent_id]).first
if existing_child.present?
existing_child.update_attributes(attribute: value_1)
else
#child = #parent.child.build(child_params)
end
#other saving related code goes here.
end
This is just a basic piece of example.
Try creating separate instance methods to keep the Contrller DRY. :)

id nil when select model without no relation

I have a model with no relation.
class GridConfig < ActiveRecord::Base
end
my question is why result of query are appended id:nil columns?
GridConfig.select(:fontSize)
result is
#<GridConfig id: nil, fontSize: "12px">
is there any options for this?
thank you.
I want find some records and pick certain columns. and send to client.
user_key = params[:user_key]
grid_id = params[:grid_id]
#config = GridConfig.where(['user_key = ? and grid_id = ?', user_key, grid_id])
.select(:model_id, :fontSize, :displayCount, :columnModel)
# i checked #config variables at this point and found nil:id...
#config = #config.index_by(&:model_id)
# and i want to this makes indexed by model_id like [{"model":{...}},{"model2" : {...}}, {}]
respond_to do |format|
format.json { render json: #config }
end
You can use the pluck method to select only certain columns into an array, then index by the first column.
#config = GridConfig.where(user_key: params[:user_key], grid_id: params[:grid_id])
.pluck(:model_id, :fontSize, :displayCount, :columnModel)
#config = #config.index_by{ |x| x[0] }

autocomplete through Array of strings in Rails 4

I'm using this gist to build autocomplete functionality in my Rails app.
I'm saving record in Shoe model attribute like below
"nike air, nike steam,nike softy ,nike strength" #comma separated words
My controller code is below
def shoes
shoes_list = []
shoes = Shoe.all
shoes.each do |shoe|
shoes_list << shoe.model.split(',')
end unless shoes.blank?
if params[:term]
like = "%".concat(params[:term].concat("%"))
# shoes = Shoe.where("model like ?", like)
# **How i make like query to "shoes_list" same like above commented line?**
else
shoes = Shoe.all
end
list = shoes.map { |u| Hash[id: u.id, label: u.model, model: u.model] }
render json: list
end
How do I render it in json format?
At last this code works for me.
def shoes
shoes_list = []
shoes = Shoe.all
shoes.each do |shoe|
shoes_list << shoe.model.split(',')
end unless shoes.blank?
shoes_list.flatten!
if params[:term]
shoes = shoes_list.grep(Regexp.new( Regexp.escape(params[:term]), "i" ))
else
shoes = shoes_list
end
list = shoes.map {|u| Hash[id: u, label: u, name: u]}
render json: list
end
Also see How get value from array of strings in Ruby 2.0

Resources