4

I have a Posts resource, and a User Rating resource.

In my routes.rb, I have nested the user rating within the posts:

jsonapi_resources :posts do
  jsonapi_resources :user_ratings
end

This has exposed the endpoint /posts/{id}/user-ratings correctly.

However when testing this end point with an {id}, it is returning all user-ratings, not just the user-ratings associated to that post id.

In my posts resource, I have tried adding: has_many :user_ratings, in user ratings I have tried adding: has_one :post.

In my models, I have added has_many and belongs_to.

Yet nothing I have tried is making the api return just the user ratings associated with a particular post id.

Any insight would be appreciated, thank you.

anothermh
  • 9,815
  • 3
  • 33
  • 52
zark0
  • 41
  • 4

3 Answers3

3

There is a special construction for related resources, in routes.rb:

jsonapi_resources :posts do
  jsonapi_related_resources :user_ratings
end

Post resource should have

has_many :user_ratings

It will add route /posts/{id}/user_ratings and ratings will be fetched through post resource, you can also override records_for_* method there to get more control:

def records_for_user_ratings
   super.published
end
biomancer
  • 1,284
  • 1
  • 9
  • 20
1

In the UserRating model try a has_one :issue

In routes.rb, you don't need to nest user_ratings in posts

When you run rake routesyou should see nesting posts\:post_id\user_ratings even though in routes.rb its not specified as nested

galiat
  • 54
  • 1
  • 4
-4

Make sure the index action of the controller uses that post_id parameter to filter user_ratings. For example:

    # GET /user_ratings
    def index
      @post = Post.find(params[:post_id])
      @user_ratings = @post.user_ratings

      render json: @user_ratings
    end

Hope that helps.

Hatem Mahmoud
  • 403
  • 6
  • 9