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:
-> {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.