Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
    Gabriel Fortuna
    @gee-forr
    hey all (and @lgebhardt in particular :) ) I'm very happy that I've started a new project, and get to work with JR again... I've got a small problem though. We've moved away from exposing database primary keys as the external facing id for our records, and have started using HashIDs.
    13 replies
    Gabriel Fortuna
    @gee-forr
    rats... i've gone through the code, and it looks like there's a big implicit reliance on a hardcoded .id field pretty much everywhere. I don't think what I'm asking for above is possible without a major refactor to JR. Is my assessment correct, @lgebhardt ?
    Joe Gaudet
    @joegaudet
    @lgebhardt ever thought of using something like this to optimize JR. https://blog.crunchydata.com/blog/generating-json-directly-from-postgres
    You’d probably need to mark a resource as comming directly from the DB.
    RobL
    @braindeaf
    Hey, couple of questions if I may. Is ActiveRecord going to be required from now on. We have two apps that don't use it and therefore this is going to be something we'll need to hack
        def process_operations(transactional)
          if transactional
            run_callbacks :transaction do
              ActiveRecord::Base.transaction do
                yield
              end
            end
          else
            begin
              yield
            rescue ActiveRecord::Rollback
              # Can't rollback without transaction, so just ignore it
            end
          end
        end
    RobL
    @braindeaf

    Secondly, I'm trying to set up a singleton resource

    class Api::V1::MeResource < JSONAPI::Resource
      model_name 'User'
    
      singleton singleton_key: (lambda do |context|
        key = context[:current_user].try(:id)
        raise(JSONAPI::Exceptions::RecordNotFound, nil) if key.nil?
    
        key
      end)
    
      attributes :uuid, :full_name, :email
    
      relationship :tenant, to: :one
    end

    by default the resource is assumed to be a 'me', I want it to be 'users'. But maintain /api/v1/me

    {
      "data": {
        "id": "000001",
        "type": "mes",
        "links": {
          "self": "https://demo.test/api/v1/mes"
        },
        "attributes": {
          "uuid": "ef242d051684",
          "full_name": "Mr Rob Lacey",
          "email": "rob.lacey@fluff.co.uk"
        },
        "relationships": {
          "tenant": {
            "links": {
              "self": "https://demo.test/api/v1/mes/relationships/tenant",
              "related": "https://demo.test/api/v1/mes/tenant"
            }
          }
        }
      }
    }

    This fixes the type, but in order to support /me/relationships/tenant the urls can't be using /users, that's the job of UserResource, etc

    
      def self._type
        :users
      end

    So this is weird now. I am not even user the links should point at a nested relationship if tenant is also a first class citizen at /api/v1/tenants/1

    {
      "data": {
        "id": "000001",
        "type": "users",
        "links": {
          "self": "https://demo.test/api/v1/users"
        },
        "attributes": {
          "uuid": "ef242d051684",
          "full_name": "Mr Rob Lacey",
          "email": "rob.lacey@fluff.co.uk"
        },
        "relationships": {
          "tenant": {
            "links": {
              "self": "https://demo.test/api/v1/users/relationships/tenant",
              "related": "https://demo.test/api/v1/users/tenant"
            }
          }
        }
      }
    }
    Antonis Tzorvas
    @atzorvas
    where would you test your immutable resources? (the fact that’s immutable)
    in a request or resource spec?
    Ekkehard Ehrenstein
    @Ekkstein
    Hello Everybody. Im new and unexperienced, guidance and advice is welcome. To my question. I have added the gem to my repo and am now receiving segmentation faults. First on ruby 2.6.5p114 when using a resource generator. Then I upgraded to ruby 2.7.0 and this segmentation fault disappeared. Instead I am now getting them when I shut down the console or the dev server. This gem would be a huge help in my development timeline. Can anybody please help me with this?
    Antonis Tzorvas
    @atzorvas
    how can I disable index action? :eyes:
    My understanding is that I’d have to override the method in ResourceController and raise from there only: [:show]
    john
    @john:fireballxl20.com
    [m]
    Hello, is there a reason that belongs_to is deprecated in favor of has_one? Why not match the ActiveRecord api?
    Artur
    @artur79
    hi, what approach do you use to set in resource class attributes dynamically ? I'm trying attribute -> { ldap_auth_bind_key_field }, if: :uses_ldap? but got error undefined method `to_sym' for #<Proc:0x00007f7f3ca773b8. Second part after if: works
    Artur
    @artur79
    I'v got of course defined, self.ldap_auth_bind_key_field class method
    Artur
    @artur79
    I'd like to prevent error 500 and use own one in case when one of the tags does not exist, is there any way to prevent it, at the moment I get
    [www] [3cd0412f-be18-4dd7-b971-15a2fb60e52e] Internal Server Error: Couldn't find all Tags with 'id': (2, 4818192505) (found 1 results, but was looking for 2). Couldn't find Tag with id 4818192505. /bundle/vendor/ruby/3.0.0/gems/activerecord-6.1.4/lib/active_record/relation/finder_methods.rb:362:in `raise_record_not_found_exception!' /bundle/vendor/ruby/3.0.0/gems/activerecord-6.1.4/lib/active_record/associations/collection_association.rb:69:in `ids_writer' /bundle/vendor/ruby/3.0.0/gems/activerecord-6.1.4/lib/active_record/associations/builder/collection_association.rb:66:in `tag_ids=' /bundle/vendor/ruby/3.0.0/gems/jsonapi-resources-0.10.4/lib/jsonapi/basic_resource.rb:1104:in `call' /bundle/vendor/ruby/3.0.0/gems/jsonapi-resources-0.10.4/lib/jsonapi/basic_resource.rb:1104:in `block in define_foreign_key_setter' /bundle/vendor/ruby/3.0.0/gems/jsonapi-resources-0.10.4/lib/jsonapi/basic_resource.rb:322:in `_replace_to_many_links' /bundle/vendor/ruby/3.0.0/gems/jsonapi-resources-0.10.4/lib/jsonapi/basic_resource.rb:90:in `block in replace_to_many_links' /bundle/vendor/ruby/3.0.0/gems/jsonapi-resources-0.10.4/lib/jsonapi/basic_resource.rb:60:in `block in change' /bundle/vendor/ruby/3.0.0/gems/activesupport-6.1.4/lib/active_support/callbacks.rb:98:in `run_callbacks'
    not sure actually is it triggered by rails side or jsonapi resources one
    Ruben Santos
    @soltex1
    anyone knows how to fix this issue: undefined method 'serialize_to_hash' for #<JSONAPI::ResourceSerializer:0x00007f4cfc8ba240>
    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.