简体   繁体   中英

Rails JSON API: limit has_many relationship to current_user

I have a rails json API with 2 models ( Bags and Items ). I am using active record serializers with MySQL to organize the json output. I want to show all Bags for all users, but only Items for the current user.

Looking for something like this:

class Bag < ActiveRecord::Base
  has_many :items,-> {where current_user: "#{current_user.id}"},class_name: 'Items'
end

I don't know of a way to pass the current_user.id property to the model. Hoping someone knows a way.

Two things:

  1. You can't access controller and helper methods directly in your models. You need to pass them to your model. An easy way of doing it would be to add a method or a scope.
  2. Association query customization does not support argument passing to your block ( -> {where current_user: ... ). So, you can't do it in association declaration.

So, I guess you would have to add a scope:

class Bag < ActiveRecord::Base
  has_many :items
  scope :user_items, ->(user) { where(items: {current_user: user}) }
end

PS. You don't need to convert "#{current_user.id}" to a string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM