Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
    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.
    Manuel Lorenzo
    @noloman

    hi all! I'm trying to create a wrapper API around a third party API and I'm using the jsonapi-resources. I have a very simple JSON resource which is a Job and this is part of my controller:

    class JobsController < JSONAPI::ResourceController
      skip_before_action :verify_authenticity_token
    
      def index
        jobs = fetch_jobs
        render json: serialize_jobs(jobs)
      end
    
      private
    
      def serialize_jobs(jobs)
        serializer = JSONAPI::ResourceSerializer.new(JobResource)
        serializer.serialize_to_hash(JobResource.new(jobs, nil))
      end
    
      def fetch_jobs
        response = Faraday.get('https://remotive.com/api/remote-jobs?limit=1')
        return nil if response.status != 200
    
        JSON.parse(response.body)
      end

    However, I'm getting the following error:

    NoMethodError in JobsController#index
    undefined method `serialize_to_hash' for #<JSONAPI::ResourceSerializer:0x00000001106ae328 @primary_resource_klass=JobResource...
    Joe Gaudet
    @joegaudet
    @noloman I believe the interface for that changed in .10
    Andy Vanasse
    @andyvanasse_twitter
    @noloman swap 'Job' for 'Project' below and it should work in v0.10. A couple of quick notes on it. First, this code will not render relationships (which doesn't sound like a problem). Second, in the second line you can omit url_helpers: self if you do not need/want to render links.
        def render_project_json(project)
          resource = ProjectResource.new(project, { account: project.account })
          serializer = JSONAPI::ResourceSerializer.new(ProjectResource, url_helpers: self)
          render json: { data: serializer.object_hash(resource, {}) }, status: :ok
        end
    Code Apprentice
    @codeguru42
    I have used Serializers in the past for a custom endpoint that doesn't quite fit in the typical CRUD model. This is great to leverage jsonapi-resources to maintain the same schema for these endpoints. Is there any class to do the opposite? If I have a JSON string that follows the JSON:API spec, can I easily deserialize it into a resource or active record object?
    Cory Loken
    @cloke
    I was curious if anyone has some thoughts about this issue (specifically I added a lot more at the bottom). We are trying to upgrade our app from v.9 but the gem seems to get confused with schemas and relationships. At this point I know what is happening, but don't understand the internals of ActiveRelationships to know how to fix. cerebris/jsonapi-resources#1369
    Dipen
    @dtrce
    is anyone using ksuid with jsonapi-resources? I'm getting an error when I have key_type :ksuid in my resource file.
    Error is
     User Load (0.1ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ?  [["id", "user_2EB6fmWlQKSwKy72DsNKJjRisRq"]]
    Internal Server Error: undefined method `[]' for nil:NilClass
    
              relationship_data = @resource_klasses[resource_klass][resource.id][:relationships]
                                                                                ^^^^^^^^^^^^^^^^ /Users/dtrce/.rvm/gems/ruby-3.1.1/gems/jsonapi-resources-0.10.7/lib/jsonapi/resource_set.rb:96:in `block (2 levels) in populate!'
    Dipen
    @dtrce
    I'm using https://github.com/michaelherold/ksuid-ruby#with-a-ksuid-primary-key with rails to use that as primary key
    Dipen
    @dtrce
    so did some debugging and it seems that it's failing because resource.id.class.name is KSUID::Prefixed
    Dipen
    @dtrce
    and the map has it as string
    Coley Brown
    @coleyb
    Hey all! Curious if anyone has any recommendations for auto-generating docs for my json-api resources API. It seems like they would be easy to infer from the routes but didn't see anything built into the library.
    Joe Gaudet
    @joegaudet
    There isn’t, but it’s pretty easy to reflect on the resources and get most of the details.
    I generate a client.
    Robert Mihail Damoc
    @robert-damoc

    Hello. I am trying to create a resource for my app, but I get the error: undefined method 'delegated_field_name' for nil:NilClass

    # Models
    class Recipe < ApplicationRecord
      has_many :ingredients_recipes
      has_many :ingredients, through: :ingredients_recipes
    end
    
    class IngredientsRecipe < ApplicationRecord
      belongs_to :ingredient
      belongs_to :recipe
    end
    
    
    # Resources
    class RecipeResource < JSONAPI::Resource
      # ...
    
      has_many :ingredients_recipes
    end
    
    class IngredientsRecipeResource < JSONAPI::Resource
      attributes :quantity
    
      belongs_to :recipe
    end

    The call I'm doing in the browser is http://localhost:3000/recipes?page[size]=1&include=ingredients-recipes
    First line of the error: Internal Server Error: undefined method 'delegated_field_name' for nil:NilClass /Users/robert/.rbenv/versions/3.0.3/lib/ruby/gems/3.0.0/gems/jsonapi-resources-0.10.7/lib/jsonapi/active_relation_resource.rb:866:in 'get_aliased_field'

    Was unable to find anything online

    2 replies
    Shrinath Aithal
    @shrinathaithal
    Hello all. In 0.9.0, we were able to declare has_many: :xyz and then later in some custom method I could call xyz.id or delegate :someabc, to: :xyz. This isn't allowed anymore in 0.10.7?
    5 replies
    Joe Gaudet
    @joegaudet
    Is there a way to let JR know that a field is virtual and so not make it use pluck when using sparse field sets?
    Oh seems like it’s sort that’s the problmem
    Artur
    @artur79
    hi, I'v got 2 models OnlineAppraisal and OnlineAppraisal70, is there any way to use only one resource for both ? I guess it should be specified somehow in controller or routes, before resource is reached.
    Artur
    @artur79
    problem is that also I need to stick with 0.9 because I use mongodb and since 0.10 jsonapi resources seem to be even more wired to ActiveRecord
    Artur
    @artur79
    got solution, kinda hacky but works
    in resource class add:
      def self.resource_for(type)
        type = 'online_appraisal' if type.to_s == 'online_appraisal70'
    
        super
      end
    tried also with just
       def self._type
         :online_appraisals
      end
    but above resolved problem must partialy, _type in response was correct but self_link still was not build. First hack resolves both