Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
    Ruben Santos
    @soltex1
    here's what I am doing: JSONAPI::ResourceSerializer.new(ProjectTypeResource).serialize_to_hash(ProjectTypeResource.new(ProjectType.find(1), nil))
    Ruben Santos
    @soltex1
    it looks like adding gem 'jsonapi-resources' to the Gemfile will install the version 0.10.5, that one doesn't contain the method serialize_to_hash, so not sure why the documentation are using a method that is not present in the latest version
    Joe Gaudet
    @joegaudet
    I think it was added back in, might not be on release yet.
    @soltex1 ^^^
    Ruben Santos
    @soltex1
    @joegaudet thank you for letting me know! I ended up using an older release
    Joe Gaudet
    @joegaudet
    @soltex1 should give edged a go, the caching and lookup is quite a bit feaster.
    Joe Gaudet
    @joegaudet
    @lgebhardt observing something weird, seems read_multi on the cache adapter is trimming my dates that have been formatted to include higher precision.
    Screen Shot 2021-08-24 at 12.04.50 PM.png
    Screen Shot 2021-08-24 at 12.05.13 PM.png
    Not really sure how it would do that.
    Joe Gaudet
    @joegaudet
    Nevermind, I figured it out.
    Ignore me.
    Anuj Patel
    @patelanuj28
    Anyone knows the good library to parse JSON API response via ruby gem?
    There is one in javascript: https://github.com/beauby/jsonapi-datastore however I am looking for similar for ruby
    Appreciate for recommendation
    Joe Gaudet
    @joegaudet
    @lgebhardt since upgrading to rails 6, while still on .9 branch we observe some very strange caching behaviours, are you aware of anything that could be causing that?
    Were there changes to the caching mechanism we aren’t taking into account?
    Vinícius
    @vinidotdev

    Hi, everyone. Could you help me? I have the following context

    class Country < ApplicationRecord; end
    
    class Brazil < Country; end # and many others
    class Api::V4::CountryResource < JSONAPI::Resource
      immutable
      model_name 'Country'
      attributes :name
    end

    When I hit /api/v4/countries?page%5Bnumber%5D=1&page%5Bsize%5D=100 it returns

    "exception": "JSONAPI: Could not find resource 'brazil'. (Class Api::V4::BrazilResource not found)",
    Vinícius
    @vinidotdev
    So, I created all countries resources and it works
    Vinícius
    @vinidotdev
    "data": [
            {
                "id": "1",
                "type": "brazils",
                "attributes": {
                    "name": "Brasil"
                }
            },
            {
                "id": "2",
                "type": "mexicos",
                "attributes": {
                    "name": "México"
                }
            }
    }...
    But it is not the best solution
    Avery Bloom
    @averydev
    Hi there! I was looking for a way to do a filter but only return a single record rather than a set of records but couldn't sort out a syntax that did what i was expecting. I'd appreciate suggestions!
    Returning a single record from a filter throws an error looking for the .order method
    David Valaz
    @davidvalaz

    Hey All! Happy evening from over here in London.

    Seem to be getting a weird error when I try to version my API. Running rails server throws up this error:

    /Users/David/.asdf/installs/ruby/3.0.0/lib/ruby/gems/3.0.0/gems/zeitwerk-2.4.2/lib/zeitwerk/loader/callbacks.rb:18:in `on_file_autoloaded': expected file /Users/David/Code/Ruby/my_project/app/controllers/connector_controller.rb to define constant ConnectorController, but didn't (Zeitwerk::NameError)

    Everything works just find when I don't start adding module Api and module V1 to my classes

    David Valaz
    @davidvalaz
    Oh and I'm using v10 btw
    matt_strayer
    @matt_strayer:matrix.org
    [m]
    Hi there -- I was wondering if anyone could point to a guide for resource inheritance. I can't seem to get things working as I would expect them to work.
    BaseResource for me would just be responsible for setting the PK of the resource
    Immutable resource would inherit from that and then just add the immutable tag to the resource.
    Then all other real resources would inherit from one of these two, depending on if they are mutable or not.
    Iuval
    @iuval
    Hi all! I'm using v0.10 and trying to a new meta field on an index.
    I need to have the sum of a specific field for all records despite the pagination.
    Looking at the guide for v0.9 looks like custom Processors is the way to go but I haven't found access to all the records from there.
    Any idea how to approach this? Thanks!
    ldvm
    @ldvm:matrix.org
    [m]

    Hi everyone! I'm noticing that overriding records to only return a scope doesn't propagate to the metadata in the response:

    def self.records(options = {})
        Model.scope
      end

    results in records still being returned in the meta result "filtered" total even when all records are filtered out.

    My question is: how can I preserve the record filtering/scoping behavior while preserving accurate metadata

    2 replies
    ldvm
    @ldvm:matrix.org
    [m]

    :point_up: Edit: Hi everyone! I'm noticing that overriding records to only return a scope doesn't propagate to the metadata in the response (on 0.10.4):

    def self.records(options = {})
        Model.scope
      end

    results in records still being returned in the meta result "filtered" total even when all records are filtered out.

    My question is: how can I preserve the record filtering/scoping behavior while preserving accurate metadata

    David Cantu
    @dcantu96

    Hi im trying to create a new "sponsor" with a belongs_to or "has_one" relationship called "user"
    I am using JR v0.10.5
    Rails 6.1.4
    ruby 3.0.1
    this is the POST

    Started POST "/api/v1/sponsors" for ::1 at 2021-10-20 18:43:48 -0500
    Processing by Api::V1::SponsorsController#create as JSON
    Parameters: {"data"=>{"type"=>"sponsors", "attributes"=>{"status"=>"inactive", "rfc"=>"234234-234", "job"=>"example job", "user"=>{"id"=>"472", "type"=>"users"}}}}

    I am getting this error

    Internal Server Error: no implicit conversion of nil into Hash /Users/..... jsonapi-resources-0.10.5/lib/jsonapi/basic_resource.rb:835:in `merge'

    This is my SponsorResource

    class Api::V1::SponsorResource < JSONAPI::Resource
      attributes :status, :rfc, :job, :notes
      has_one :user
    end

    Does anyone have an idea of what could be wrong?

    4 replies
    Iuval
    @iuval
    Hello again. I need to do something in the index action, so when a certain condition is met the response should empty 200 and enque a background job that send content by email as a csv. When the condition is not met it should run as usual. Does anybody know how can we achieve this? We are currently using a custom ResponseDocument to download either csv or jsonapi data, but we need to make writing csv an async job.
    reachire-smendola
    @reachire-smendola
    @Julius-Rapp @atsjj , did you ever get resolution on the error undefined methodrelationship' for "":String /usr/local/bundle/bundler/gems/jsonapi-resources-25911bc19871/lib/jsonapi/path_segment.rb:33:in eql?` I'm currently having this problem. Should I file a bug report? Thanks!
    2 replies
    ZoWellDev
    @ZoWellDev

    Hey there, I have an issue using the apply callable on a filter, it won't work and keeps applying it directly on my records.
    I have this:

      filter :"is_cleaning_related",  apply: -> (records, value, _options) {
        records.cleaning_related(value[0].to_s.downcase == "true")
      }

    (The method cleaning_related is a scope I made on the concerned record that takes a boolean as a parameter)
    It keeps throwing me an error that says "audits.is_cleaning_related column does not exist" (audit is the model) which is true but it should be calling my scope instead of looking for that column. Can anyone help please? I feel like this is caused by a dumb mistake but I couldn't find it.

    Xavier Hocquet
    @xhocquet
    Hey there, I was going through search results but could not find a clear answer. Does the gem support updating a to-many relationship's attributes? For example I have an author with multiple blog posts. I know I can associate/disassociate the posts with an update on the author's relationship. Can I change an attribute (like publish date) in bulk for multiple blog posts through the same update call? Logic here seems to only pull ID + type.
    Chase Stubblefield
    @chasestubblefield

    Hello, I'm trying to do something similar to Flattening a Rails Relationship in the docs, and running into an N+1 situation. Let's say I have something like:

    class PostResource < JSONAPI::Resource
      def name
        "#{@model.name} - #{@model.author.name}"
      end
    end

    I don't want an AuthorResource, posts are the only thing I want accessible from the API, with no evidence that another db table is involved. But how do I prevent N+1 queries in this case? I want to modify whatever relation is used to fetch records to add includes(:author). Here's what I've tried:

    def self.records(options = {})
      super(options).includes(:author)
    end

    Hitting the index still produces too many queries. Is there a different method I need to override? Or is there something in the docs I missed? The behavior around eager loading seems built for resource relationships, but not necessarily model relationships.

    1 reply
    Connor Handerhan
    @chanderhan
    cerebris/jsonapi-resources#1307 looks promising for authorization.
    Is it likely to be merged?
    2 replies
    Luke Melia
    @lukemelia

    Hi folks, I'm investigating upgrading our Rails app from from JR 0.9 to 0.10 and have identified some blockers. I'm wondering whether others in this group have found workarounds for these issues, or whether they are upgrade blockers for other people too:

    1) Incompatibility with jsonapi_authorization gem (venuu/jsonapi-authorization#64)
    2) Standalone serialization. Illustrated here: https://gist.github.com/lukemelia/aefe8fde7e8e2be5d6e4fa4fab74fecf
    3) Backing resources with non-ActiveRecord objects
    4) Relationship on a resource that is programmatically populated (via records_for_... rather than having a relationship defined on the underlying model.

    Have you run into these issues? How did you deal with them?

    5 replies
    Thomas Scholz
    @tscholz
    Hi, is it still the case that associations of namespaced resources are limited to the same namespace? If so, is there a good way to denormalize fields from different models into a resource without getting too much database queries?
    6 replies
    Code Apprentice
    @codeguru42

    I am getting

         NoMethodError:
           undefined method `each_key' for nil:NilClass
         # /Users/me/.rbenv/versions/2.7.3/gemsets/blog-api/bundler/gems/jsonapi-resources-bf4b4cd7d79d/lib/jsonapi/resource_set.rb:37:in `populate!'
         # /Users/me/.rbenv/versions/2.7.3/gemsets/blog-api/bundler/gems/jsonapi-resources-bf4b4cd7d79d/lib/jsonapi/resource_serializer.rb:49:in `serialize_to_hash'
         # ./app/controllers/articles_controller.rb:4:in `latest'
         # ...

    when trying to serialize an ActiveRecord object:

    class ArticlesController < JSONAPI::ResourceController
      def latest
        serializer = JSONAPI::ResourceSerializer.new(ArticleResource)
        serializer.serialize_to_hash(Article.latest)
      end
    end

    (full MCVE: https://github.com/codeguru42/blog-api)
    What am I doing wrong?

    2 replies
    David A. Lee
    @davidalee
    when side-loading a resource, I noticed that self.records doesn't get called on the resource being side-loaded. is there another way to access the side-loaded records?
    4 replies
    Code Apprentice
    @codeguru42

    I'm attempting to submit an issue. I see your template to recreate the issue at https://github.com/cerebris/jsonapi-resources/blob/master/lib/bug_report_templates/rails_5_latest.rb. When I copy it to a local file and run it, I get

    Revision rails-5 does not exist in the repository https://github.com/jruby/activerecord-jdbc-adapter. Maybe you misspelled it?

    It looks like activerecord-jdbc-adapter no longer has a rails-5 branch. Is it ok to just remove the branch: 'rails-5' parameter? I assume that just assumes master. Would you accept a PR if I update that in the template?

    Larry Gebhardt
    @lgebhardt
    If you can fix the template that would be very much appreciated. Thanks!
    1 reply
    Nico
    @nicoayala

    Hi folks, I'm having an issue while filtering relationships I'm not sure how to solve. These are the resources:

    class UserResource < JSONAPI::Resource
      has_many :tasks
    end
    
    class TaskResource < JSONAPI::Resource
      has_one :reminder
    
      filter :reminder_due_date, apply: ->(records, value, _options) {
        # puts records.to_sql
        records.joins(:reminder).
          where(reminder: { due_date: value[:from]..value[:to] })
      }
    end

    When I request GET /users/1/tasks?filter[reminder_due_date][to]=2022-02-01 it results in a 500 with the error Can't join 'User' to association named 'reminder'; perhaps you misspelled it?

    The output of puts records.to_sql effectively shows that the provided records param is a query to the users table. I was just trying to filter the tasks and not the users. Is this the right approach?

    What else am I missing? Thx in advance!

    5 replies
    Code Apprentice
    @codeguru42

    @lgebhardt I made a PR for the project templates to fix the one problem I found, but while I'm at it, I might as well clean up more. I have a few questions in that regard:

    1. There are two templates in lib/bug_report_templates. Do you want to continue maintaining both? Or are you ok with consolidating to one? If so, which one?

    2. The template has gem 'rails', require: false. Is this intentional? Would it make more sense to remove the require: false so that rails is installed when this script is run?

    3. Similarly, we have gem 'jsonapi-resources', require: false. Should we remove require: false here?

    David A. Lee
    @davidalee
    This message was deleted
    1 reply
    Code Apprentice
    @codeguru42
    @lgebhardt Any guidance for my previous questions?
    Vincent Smith
    @Vince-Smith

    Hey all, wondering if anyone has dealt with this or has any recommendations:

    I'm toying with creating a resource that:

    • Is not backed by an active record
    • Is related to numerous collections of the same resource

    Realistically this could be achieved with multiple API calls using different filters, but I'm looking into options to do this a single request while still leveraging the resource caching in jsonapi-resources

    An example of this might be a collection of events, grouped into collections of recommended-events, popular-events, and trending-events

    {
      "data": [
        {
          "attributes": {
            "sort-order": ["popular", "trending", "recommended"]
          },
          "id": "<some-guid>",
          "relationships": {
            "popular-events": {
              "data": [
                { "id": "100", "type": "events" }
              ]
            },
            "trending-events": {
              "data": [
                { "id": "101", "type": "events" },
                { "id": "102", "type": "events" }
              ]
            },
           "recommended-events": {
              "data": []
            }
          },
          "type": "event-listings"
        }
      ],
      "included": [
        {
          "attributes": {
            "name": "Comic-Con"
          },
          "id": "100",
          "type": "events"
        },
        {
          "attributes": {
            "name": "Super Bowl"
          },
          "id": "101",
          "type": "events"
        },
        {
          "attributes": {
            "name": "Olympics"
          },
          "id": "102",
          "type": "events"
        }
      ]
    }

    I'm familiar with making a resource that isn't backed by a model, but having a hard time figuring out where to start with leveraging caching and includes in this case.

    Thanks in advance!

    Andy Vanasse
    @andyvanasse_twitter
    @lukemelia thought you might be the most likely to be able to help here. I'm attempting to roll some local authorization. For one scenario, I was considering a before_xxx callback on the resource and raising an exception, with the intent to use rescue_from in a Rails controller, not unlike what I'd do with Pundit elsewhere. For reasons that I do not yet understand, however, the exception never bubbles up to the controller. At least the rescue_from never kicks in.
    I have tested this only in development and set config.consider_all_requests_local to false for dev but it still does not make it to the handler. Any ideas on why that would be? Is jsonapi-resources swallowing exceptions somewhere?
    Andy Vanasse
    @andyvanasse_twitter
    NVM, I tracked down config.exception_class_whitelist and added my custom authorization error.