How to avoid rails as_json creating flood of database requests - sql

I have a model questions that has many tags through another model question_tags. I am trying to write an api endpoint that returns a list of questions and for each question a list of it's related tag's name and id.
I'm currently using;
render json: #questions.as_json(include: {
tags: { only: %i[id name] }
})
But this runs a separate db request for every question in questions is there an alternative that will result in a smaller number of database requests?

The standard N+1 queries fixes should work here, which in Rails is eager loading.
In this case you can use include to preload the associated tags:
render json: #questions.includes(:tags).as_json(
include: {
tags: { only: %i[id name] }
}
)
You can read more about this in the dedicated rails guide section: Eager Loading Associations

Related

How do I filter fields with Directus

Let's say I make an api call like this
const { data } = await client.getItems(`module/${module.id}`, {
fields: [
'questions.module_question_id.question_text',
'questions.module_question_id.slug',
'questions.module_question_id.type',
'questions.module_question_id.answer_options.*',
],
});
I am grabbing the fields, but I also want to filter out a certain question ala its slug, is there a way to do this at the api level? I know filters exist as a global query api, but have not found examples of them being used in conjunction with fields.
Perhaps you are looking for deep? This should allow you to filter on a deeply nested relational field.
https://docs.directus.io/reference/api/query/#deep

Shopify API post one product in multiple collections

we're managing a marketplace in Shopify, and we're doing a lot of calls. We'd like to improve the number of calls and one of the keypoints is when we introduce the product in collections. One product can be inserted in multiple collections, and we do this for each post/collection:
public function pushCollection($shopifyProductId, $collectionId)
{
$collectData = [
"product_id" => $shopifyProductId,
"collection_id" => $collectionId
];
$this->client->Collect()->post($collectData);
return;
}
The question is, is there any way to post 1 product in multiple collections with a single call?
Thank you so much
You cannot do that. But if you can accumulate products to add to collections you can add multiple products to a collection in a single call.
see https://help.shopify.com/api/reference/customcollection#update
I am a little late to answer but you can add one product to multiple collections in a single API call using Shopify's GraphQL API. Here's the documentation on it: https://help.shopify.com/en/api/graphql-admin-api/reference/mutation/productcreate
The GraphQL API call to add an already existing product to already existing multiple collections would look something like this:
mutation {
productUpdate( input:
{
$id:"gid://shopify/Product/{shopifyProductId}"
collectionsToJoin:["gid://shopify/Collection/{collectionId1}","gid://shopify/Collection/{collectionId2}" ]
})
{
product{
id
}
}
}

Unable to use Ember data with JSONAPI and fragments to support nested JSON data

Overview
I'm using Ember data and have a JSONAPI. Everything works fine until I have a more complex object (let's say an invoice for a generic concept) with an array of items called lineEntries. The line entries are not mapped directly to a table so need to be stored as raw JSON object data. The line entry model also contains default and computed values. I wish to store the list data as a JSON object and then when loaded back from the store that I can manipulate it as normal in Ember as an array of my model.
What I've tried
I've looked at and tried several approaches, the best appear to be (open to suggestions here!):
Fragments
Replace problem models with fragments
I've tried making the line entry model a fragment and then referencing the fragment on the invoice model as a fragmentArray. Line entries add to the array as normal but default values don't work (should they?). It creates the object and I can store it in the backend but when I return it, it fails with either a normalisation issue or a serialiser issue. Can anyone state the format the data be returned in? It's confusing as normalising the data seems to require JSONAPI but the fragment requires JSON serialiser. I've tried several combinations but no luck so far. My line entries don't have actual ids as the data is saved and loaded as a block. Is this an issue?
DS.EmbeddedRecordsMixin
Although not supported in JSONAPI, it sounds possible to use JSONAPI and then switch to JSONSerializer or RESTSerializer for the problem models. If this is possible could someone give me a working example and the JSON format that should be returned by the API? I have header authorisation and other such data so would I still be able to set this at the application level for all request not using my JSONAPI?
Ember-data-save-relationships
I found an add on here that provides an add on to do this. It seems more involved than the other approaches but when I've tried this I can send the data up by setting a the data as embedded. Great! But although it saves it doesn't unwrap it correct and I'm back with the same issues.
Custom serialiser
Replace the models serialiser with something that takes the data and sends it as plain JSON data and then deserialises back into something Ember can use. This sounds similar to the above but I do the heavy lifting. The only reason to do this is because all examples for the above solutions are quite light and don't really show how to set this up with an actual JSONAPI set up that would need it.
Where I am and what I need
Basically all approaches lead to saving the JSON fine but the return JSON from the server not being the correct format or the deserialisation failing but it's unclear what it should be or what needs to change without breaking the existing JSONAPI models that work fine.
If anyone know the format for return API data it may resolve this. I've tried JSONAPI with lineEntries returning the same format as it saved. I've tried placing relationship sections like the add on suggested and I've also tried placing relationship only data against the entries and an include section with all the references. Any help on this would be great as I've learned a lot through this but deadlines a looming and I can't see a viable solution that doesn't break as much as it fixes.
If you are looking for return format for relational data from the API server you need to make sure of the following:
Make sure the relationship is defined in the ember model
Return all successes with a status code of 200
From there you need to make sure you return relational data correctly. If you've set the ember model for the relationship to {async: true} you need only return the id of the relational model - which should also be defined in ember. If you do not set {async: true}, ember expects all relational data to be included.
return data with relationships in JSON API specification
Example:
models\unicorn.js in ember:
import DS from 'ember-data';
export default DS.Model.extend({
user: DS.belongsTo('user', {async: true}),
staticrace: DS.belongsTo('staticrace',{async: true}),
unicornName: DS.attr('string'),
unicornLevel: DS.attr('number'),
experience: DS.attr('number'),
hatchesAt: DS.attr('number'),
isHatched: DS.attr('boolean'),
raceEndsAt: DS.attr('number'),
isRacing: DS.attr('boolean'),
});
in routes\unicorns.js on the api server on GET/:id:
var jsonObject = {
"data": {
"type": "unicorn",
"id": unicorn.dataValues.id,
"attributes": {
"unicorn-name" : unicorn.dataValues.unicornName,
"unicorn-level" : unicorn.dataValues.unicornLevel,
"experience" : unicorn.dataValues.experience,
"hatches-at" : unicorn.dataValues.hatchesAt,
"is-hatched" : unicorn.dataValues.isHatched,
"raceEndsAt" : unicorn.dataValues.raceEndsAt,
"isRacing" : unicorn.dataValues.isRacing
},
"relationships": {
"staticrace": {
"data": {"type": "staticrace", "id" : unicorn.dataValues.staticRaceId}
},
"user":{
"data": {"type": "user", "id" : unicorn.dataValues.userId}
}
}
}
}
res.status(200).json(jsonObject);
In ember, you can call this by chaining model functions. For example when this unicorn goes to race in controllers\unicornracer.js:
raceUnicorn() {
if (this.get('unicornId') === '') {return false}
else {
return this.store.findRecord('unicorn', this.get('unicornId', { backgroundReload: false})).then(unicorn => {
return this.store.findRecord('staticrace', this.get('raceId')).then(staticrace => {
if (unicorn.getProperties('unicornLevel').unicornLevel >= staticrace.getProperties('raceMinimumLevel').raceMinimumLevel) {
unicorn.set('isRacing', true);
unicorn.set('staticrace', staticrace);
unicorn.set('raceEndsAt', Math.floor(Date.now()/1000) + staticrace.get('duration'))
this.set('unicornId', '');
return unicorn.save();
}
else {return false;}
});
});
}
}
The above code sends a PATCH to the api server route unicorns/:id
Final note about GET,POST,DELETE,PATCH:
GET assumes you are getting ALL of the information associated with a model (the example above shows a GET response). This is associated with model.findRecord (GET/:id)(expects one record), model.findAll(GET/)(expects an array of records), model.query(GET/?query=&string=)(expects an array of records), model.queryRecord(GET/?query=&string=)(expects one record)
POST assumes you at least return at least what you POST to the api server from ember , but can also return additional information you created on the apiServer side such as createdAt dates. If the data returned is different from what you used to create the model, it'll update the created model with the returned information. This is associated with model.createRecord(POST/)(expects one record).
DELETE assumes you return the type, and the id of the deleted object, not data or relationships. This is associated with model.deleteRecord(DELETE/:id)(expects one record).
PATCH assumes you return at least what information was changed. If you only change one field, for instance in my unicorn model, the unicornName, it would only PATCH the following:
{
data: {
"type":"unicorn",
"id": req.params.id,
"attributes": {
"unicorn-name" : "This is a new name!"
}
}
}
So it only expects a returned response of at least that, but like POST, you can return other changed items!
I hope this answers your questions about the JSON API adapter. Most of this information was originally gleamed by reading over the specification at http://jsonapi.org/format/ and the ember implementation documentation at https://emberjs.com/api/data/classes/DS.JSONAPIAdapter.html

Using Mongo Update and $set to insert field (throwing error)

Ok, this is probably a stupid question but I have been reading and trying different queries and for some reason I cannot get this to work without throwing an error. This is my first time working with MongoDB and it is in an RoR project. We set up charities to have a twitter handle field, but it was not put into the model originally. So we populated the DB with charities, but now none of them have the twitter handle field. I added it to the model so now all others created will have it.
My issue is when I try to update the charities already in my DB I keep getting an error pointing at $set:
namespace :add_tw_handles_fields_2013_6_13 do
desc "add_tw_handle"
task :add_tw_handle => :environment do |t, args|
# db.charity.update( { featured: false }, { $set: { tw_handle : "test"}}, false, true)
# got your 6
Charity.update({ },
{
$set: { "tw_handle": "test"}
},
{ multi: true }
})
end
end
I tried the 2 synax calls above, I was reading in these 2 docs http://docs.mongodb.org/manual/reference/method/db.collection.update/ http://docs.mongodb.org/manual/core/update/#Updating-The%24positionaloperator.
I always get this error tho:
add_tw_handles_fields_2013_6_13.rake:16: syntax error, unexpected ':', expecting tASSOC
$set: {
As far as I can tell that is the correct syntax. I am running this in the script so I don't think I need the db. before my Model name (as shown in the uncommented update) right? I am new to this, but I literally copied and pasted the example and filled out my info, and nothing. I then tried adding a query, but there is never an error until it gets to $set: and I have no idea why. It is exactly as is shown in the Mongo docs linked above.
Any insight into what my issue would be greatly appreciated.
Thanks,
Alan
The error you're getting is from Ruby, not MongoDB, because you're trying to use MongoDB's JSON syntax inside of Ruby, which Ruby does not like. :) Your update query looks fine but you need to translate it to Ruby syntax which is a bit different.
coll.update( { }, { "$set" => { "tw_handle" => "test" } } );
will work assuming coll is your Collection object.
See here for a good tutorial (written by the MongoDB Ruby team) on using the Ruby driver.
Ok so after looking around and talking to the other dev on this project this is what I have found:
Inside a rails script you want to access the objects through rails not the mongoDB directly:
Following example is for running a script from within lib/tasks
Uses Rails activerecord to update the entry through the framework
m = ModelName.find("51b610972f52760fcc003331")
m.update_attributes( :attribute_name => "what you want to assign" )
m.save
Finds the object that has the id given from your model in rails (accesses mongo db directly)
object = ModelName.find({
"$in" => {
"_id" => "51b610972f52760fcc003331"
}
})
object.first.update_attributes(:attribute_name => "what you want to assign")
From within the console
Within the rails console you can use the first segments syntax using the activerecord models to access the objects you are querying for. But if you want to go directly into the mongo console the syntax is slightly different then above.
after going to the root directory of your project launch mongo in the console and find an object from one of your collections based on its id:
>mongo
>show dbs
>use dbsname
>show collections
>db.collection_name.find({ _id: { $in: [ ObjectId("51b610972f52760fcc003331") ] }})
Hopefully this is helpful to others just learning, syntaxs are different in each. I was told that mongo console runs with javascript, where the rails console (and within the project) is using the activerecord to run the call then manipulate the MongoDB. The commenter above was only addressing accessing the mongoDB directly from within a script. So hopefully this is a little more complete in the different ways you could run into this issue.

What is the proper RESTful way to "like" something in Rails 3?

Let's say I have a Rails 3 app that displays videos. The user can "Like" or "Dislike" the videos. Also, they can like/dislike other things like games. I need some help in the overall design and how to handle the RESTful routes.
Currently, I have a Like Class that uses polymorphic design so that objects are "likeable" (likeable_id, likeable_type)
I want to do this via AJAX (jQuery 1.5). So I was thinking something like:
javascript
// these are toggle buttons
$("likeVideo").click( function() {
$.ajax({
url: "/likes/video/" + video_id,
method: "POST",
....
});
} );
$("likeGame").click( function() {
$.ajax({
url: "/likes/game/" + game_id,
method: "POST",
....
});
} );
rails controller
Class Likes < ApplicationController
def video
# so that if you liked it before, you now DON'T LIKE it so change to -1
# or if you DIDN'T like it before, you now LIKE IT so change to 1
# do a "find_or_create_by..." and return JSON
# the JSON returned will notify JS if you now like or dislike so that the
# button can be changed to match
end
def game
# same logic as above
end
end
Routes
match "/likes/video/:id" => "likes#video", :as => :likes_video
match "/likes/game/:id" => "likes#game", :as => :likes_game
Does this logic seem correct? I am doing a POST via AJAX. Technically, shouldn't I be doing a PUT? Or am I being too picky over that?
Also, my controller uses non-standard verbs. Like video and game. Should I worry about that? Sometimes I get confused on how to match up the "correct" verbs.
An alternative would be to post to something like /likes/:id with a data structure that contains the type (game or video). Then I could wrap that in one verb in the controller...maybe even Update (PUT).
Any suggestions would be appreciated.
Rest architectural style does not specify which "verb" you should be using for what. It simply says that one can use HTTP if they want to for connectors.
What you are looking for is HTTP specifications for method definitions. In particular POST is intended for:
- Annotation of existing resources;
- Posting a message to a bulletin board, newsgroup, mailing list,
or similar group of articles;
- Providing a block of data, such as the result of submitting a
form, to a data-handling process;
- Extending a database through an append operation.
while PUT:
requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server.
Which category your functionality falls into is up to you - as long as you are consistent with yourself about it.