Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
    Julius-Rapp
    @Julius-Rapp
    @rockertux relationships should be missing by default if the resource does not have any relationships defined. Alternatively, the client can use sparse fieldsets. Does that help?
    Arthur Alkmim
    @rockertux
    Hm, we do have some relationships defined but we're using them to access child fields
    I think I missed this exclude_links, thanks for pointing that!
    Arthur Alkmim
    @rockertux
    @Julius-Rapp thanks, I think I got riiight on track with that
    ManhND
    @manhnd.hebestorm_gitlab
    Hi everyone, today I added paranoia to soft-deleted, but when I tried to get index with scope with_deleted, every fields were blank
    John Malone
    @Pro777
    Has anyone figured out how to fix N+1 queries that the bullet gem recognizes in jsonapi-resource 0.10?
    John Malone
    @Pro777
    Looks like the last comment on this still works: cerebris/jsonapi-resources#634
    prasannakumar1989
    @prasannakumar1989
    Thanks for this wonderful framework. I m trying to use relationship serializer serialize_to_relationship_hash(source, requested_relationships), Can someone say what should be passed as a value requested_relationships ?
    Tobias Grasse
    @tobias_grasse_twitter
    @prasannakumar1989 Are you using 0.10.x? Looking at the code (https://github.com/cerebris/jsonapi-resources/blob/master/lib/jsonapi/resource_serializer.rb#L96), I'd say an initialized JSONAPI::Relationship class, either ToOne or ToMany.
    How you instantiate them is a different thing 😊 As I understand it, this method only serializes the given relationship, however
    prasannakumar1989
    @prasannakumar1989

    Thank you @tobias_grasse_twitter . I am evaluating 0.10 , but using 0.9

    Another question. I have a situation where the attribute name is conflicting with has_many relationship say

    attribute :tags
    
    has_many :tags

    the PATCH request seems to be in this format

    {"data":
        {    "type":"tasks",
            "id":"6",
    
            "attributes":{
                "title": "Title",
                "tags": ["Home"]
            }
        }
    }

    and expected output is in this

    {
       "data":{
          "id":"2",
          "type":"tasks",
          "attributes":{
             "title":"Updated Task Title"
          },
          "relationships":{
             "tags":{
                "data":[
                   {
                      "id":"2",
                      "type":"tags"
                   },
                   {
                      "id":"3",
                      "type":"tags"
                   }
                ]
             }
          }
       }
    }
    "included" :{ ..stuff ...}
    Thanks again for the help.
    Tobias Grasse
    @tobias_grasse_twitter
    @prasannakumar1989 Could you please share the actual output? Error or sth? I guess it's a general Rails problem because associations and attributes are both accessed as Model.methodname.
    prasannakumar1989
    @prasannakumar1989

    @tobias_grasse_twitter , I got this error

    ArgumentError: wrong number of arguments (given 1, expected 0)
    
      0) Api::V1::TaskResource 
         Failure/Error:
           it { puts JSONAPI::ResourceSerializer
                         .new(described_class)
                         .serialize_to_hash(described_class.new(sample, nil))
           }
    
         ArgumentError:
           wrong number of arguments (given 1, expected 0)
         # ./spec/resources/api/v1/task_resource_spec.rb:15:in `block (2 levels) in <top (required)>'

    My resource class definition is

    class Api::V1::TaskResource < JSONAPI::Resource
      attributes :title, :tags
    
      has_many :tags, always_include_linkage_data: true
    
    
      def tags=(tag_titles)
        @model.replace_tags!(tag_titles)
      end
    
      def self.creatable_fields(context = nil)
        super - [:tags]
      end
    
    end
    Scott González
    @scottgonzalez
    @prasannakumar1989 That’s a violation of JSON API. “...a resource can not have an attribute and relationship with the same name…” https://jsonapi.org/format/#document-resource-object-fields
    Tobias Grasse
    @tobias_grasse_twitter
    @prasannakumar1989 Ok, I meant the error message you get for your second question re: attribute and relationship with the same name. Thanks to @scottgonzalez for pointing out that in addition to probably cause conflicts with Rails' conventions, it also violates the JSON:API spec 😄 The error you shared just states that you need to pass a JSONAPI::Relationship::{ToOne,ToMany} instance to serialize_to_hash, see :point_up: 17. September 2020 15:43
    @prasannakumar1989 To be clear, the second parameter requested_relationship is only present in jsonapi-resources 0.10.x . The 0.9.x signature only requires a single TaskResource like your failing RSpec does. Maybe you mixed up the versions 😊
    I'd suggest you check out the method signature in both branches.
    John Malone
    @Pro777
    So I am working on a legacy app. We are using this gem to stand up a new public API and it is working wonderfully. I am curious if there is a way for us to leverage the jsonapi-resource classes in a new rails+erb controller.
    Tobias Grasse
    @tobias_grasse_twitter
    @Pro777 Looking at JSONAPI::Resource.initialize, I'd guess you can pass the model and an optional context (https://jsonapi-resources.com/v0.10/guide/resources.html#Context). Question is why you want to use Resource classes in such an controller?
    John Malone
    @Pro777
    @tobias_grasse_twitter The legacy app utilizes a lot of kruft that our new public API does not. By using the jsonapi-resource resource objects in the new vanilla rails frontend, we can just use the new policy objects we have created for our jsonapi.
    Dmitriy "Dima" Likhten
    @dlikhten

    Hi! I'm still on 0.9 and I was wondering if anyone can help out with this:

    I need to filter a relationship in my resource based on the context. For example:

    a person has many friends
    if I want to include person.friends.friends as an example I want to see the friends a person has and the friends they have that are mutual. Because this doesn't make sense in activerecord (this is request-specifc, not a special relationship) I would really need to make the scope records.friends.friends.where(is_friend: context[:person_id) (ignore how I build the actual where clause).

    Is this possible in 0.9?

    An alternative way to look at this:

    my PersonResource is scoped to only allow returning people who are self, or friends of whoever is in context[:person_id]. If I do include=friends.friends which is a PersonResource, the response is an error because one of the friends is not a mutual friend and thus the id is not found in the scope (and I don't want that record returned either).

    Dmitriy "Dima" Likhten
    @dlikhten

    To add a bit of context:

    Crash is in preload_included_fragments

    I assumed def records_for(association_name) would be where I can inject myself and make the necessary scoping... however that method is never invoked by the time the crash happens.

    The crash being Internal Server Error: key not found: 5735 (jsonapi/resource.rb:1354) because that key is out of scope for my resource.

    Dmitriy "Dima" Likhten
    @dlikhten
    Wondering if 0.10 solved this specific problem (I know there was a major re-do of the way relationships are queried)
    Josh Kramer
    @surjay

    Is there any way to customize relationship links? I know about the "custom_links" method/override for top-level resource links but I'm talking about the links within a relationship object. Specifically around turning a link into a JSON:API "link object". I'd like to be able to return a meta object along with the link href for things like counts. Something like this:

    "relationships": {
      "questions": {
        "links": {
          "related": {
            "href": "http://whatever.com/questions",
            "meta": {
              "count": 10
            }
          }
        },
        "data": []
      }
    }
    That or a better way to indicate counts for relationships as I've yet to find a good concensus on an approach.
    Tommy Russoniello
    @tommy-russoniello
    Josh Kramer
    @surjay

    Thanks, that might work. On a similar note, the JSON:API spec also suggests that the "relationship object" can also contain a meta object alongside "links" and "data". So something like this:

    "relationships": {
      "questions": {
        "links": {
          "related": "http://whatever.com/questions"
        },
        "data": [...],
        "meta": {
          "count": 10
        }
      }
    }

    Looking through the code and I don't see any easy way to populate/return meta at that level?

    Dmitriy "Dima" Likhten
    @dlikhten
    Idk if anyone experienced what I wrote above. Any ideas would be super helpful. Especially if someone already knows if 0.10 is the solution.
    Larry Gebhardt
    @lgebhardt
    @dlikhten I think v0.10 would make this easier, but you should be able to get this working in v0.9. Are you using subqueries?
    If you want to put together a simple test case I can try to help you get it working.
    Dmitriy "Dima" Likhten
    @dlikhten

    @lgebhardt subqueries? like you mean sq in where clauses or whatever? So basically the problem is that I override self.records in my resources to restrict what records can be seen based on my context (who is logged in). But on occasion a ?include=... includes a relationship that contains records that would otherwise be excluded by self.records. My question would be how to allow filtering of an association (including during included resources)? Typically I could do say record.association.where(...) but I don't know where in JR to put that code.

    If you need me to put together a mini-server on github to see the problem I can do that, but I was hoping that just knowing what methods exist could be a good start.

    Larry Gebhardt
    @lgebhardt
    @dlikhten In version v0.10 the way included resources are fetched should make this easier. I've got some appointments now, but I'll follow up in a few hours.
    Dmitriy "Dima" Likhten
    @dlikhten
    Thank you!
    Dmitriy "Dima" Likhten
    @dlikhten

    @lgebhardt sorry maybe I didn't quite get the meaning, what would be the right thing to override in 0.9 if you are aware of something that can be done. Currently my best plan is to remove the self.records restriction and take the serialized data and remove records from there in the processor which is definitely not the best performant way about it.

    And if 0.10 is definitely going to make things easier I will also look into it. Our only issue is some of our resources don't return db (activerecord) models which I still don't fully understand how to do in 0.10.

    Larry Gebhardt
    @lgebhardt
    FYI I mentioned in a side conversation with @dlikhten that I am working on v0.11. In that release I'd like to improve the process for non active record models and add back support for walking an eager loaded tree for the few cases where the v0.10 changes are creating problems.
    Dmitriy "Dima" Likhten
    @dlikhten
    The tl;dr of the convo
    • 0.10 solves my problem because self.records gets invoked during includes
    • 0.10 doesn't support non ActiveRecord models well, so I can't switch to it, hopeful for 0.11
    • To solve it in 0.9 I will be creating special models which join the logged in user with a nested relationship so I will have to query it directly (In the example of Hospital -> Patient -> Guardian -> Patient, I will need a HospitalGuardian with filters and HospitalPatient with filters, and won't be able to fetch the relationship directly, for now)
    reachire-smendola
    @reachire-smendola

    Hi all!
    I'm new to jsonapi-resources.
    I would like my API to have /my as an alias/shortcut to /users/{guid} where {guid} is the logged-in-user's id.
    Correspondingly, /my/someRelationship would be an alias for /users/{guid}/someRelationship
    e.g.
    GET /my/company
    GET /my/teams

    I did this:

    class MyResource < JSONAPI::Resource
      @_model_name = 'User'
      @_model_class = User
    
      has_one :company
      has_many :teams
    
      singleton singleton_key: lambda { |context|
        key = context[:current_user].try(:id)
        raise JSONAPI::Exceptions::RecordNotFound, nil if key.nil?
    
        key
      }
    end

    That works for GET /my, and it returns the JSON I would expect; the self link is /users/{guid}, which is what I actually would expect}
    companies and teams links are included in the JSON, and they also the non-shortcut URL's, which I consider "canonical"
    But as I said, I would like to be able to GET /my/company and /my/teams as well. That doesn' t work.
    I get:

    {
        "errors": [
            {
                "title": "Missing Parameter",
                "detail": "The required parameter, my_id, is missing.",
                "code": "106",
                "status": "400"
            }
        ]
    }

    Any suggestions?

    Larry Gebhardt
    @lgebhardt

    Instead of a new MyResource you could consider a route like /users/me. You could enforce this at the routes like:

    UUID_or_ME_regex ||= /[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}|([Mm][Ee])/
     jsonapi_resources :users, constraints: {:id => UUID_or_ME_regex}

    Then in the controller convert the Me to the logged in user

    ...
      before_action :convert_me_id
    
      def convert_me_id
        if params[:id] && params[:id].casecmp('me') == 0
          params[:id] = context[:current_user].id
        end
      end

    Your relationship routes would then be /users/me/company

    That has the advantage that there returned user is the same type as any other user. It also keeps it very simple

    You could also make Me and My both convert to the current user id so the route reads better /users/my/company. Still a bit "off" but not too bad in my mind
    reachire-smendola
    @reachire-smendola
    @lgebhardt, thank you for that, I do like it, and I will go with it. Nevertheless, if I would welcome suggestions on how to get /my to work as I wanted, more as a learning experience. But I will try, and probably use, /users/me .
    John Malone
    @Pro777
    I have a question about included relationships. I am expecting that the results here would return "data" -> []
    1 reply
    But I don't get any 'data' attribute at all with that relationship empty.
    Connor Handerhan
    @chanderhan
    Polymorphic belongs to
    Whoops that’s Send, not Search
    dguettler
    @dguettler_twitter
    Good Morning, does someone know if there is a way to filter included associations? E.g. a model may have many events which can be included when the model is requested. However the current user may not be allowed to see all events. Is there a way to apply a filter which events will be included.
    1 reply
    John Malone
    @Pro777
    Tobias Grasse
    @tobias_grasse_twitter
    @lgebhardt after upgrading to 0.10.x, I'm somewhat dumbfounded on how to serialize resources outside of a controller. Docs still mention serialize_to_hash, which is gone – impacts quite a few people, see cerebris/jsonapi-resources#1149 Would you or someone else be so kind to provide some guidance on the best approach? All routes I have tried (or others in that issue) have some unexpected downside or subtle errors.