开发者

How can I set conditions for polymorphic objects in a Rails query

开发者 https://www.devze.com 2023-02-01 19:01 出处:网络
I built a basic newsfeed for my website. I used a table called \"activities\" which is polymorphically related to many other objects (i.e. comments, events, status posts, etc).

I built a basic newsfeed for my website. I used a table called "activities" which is polymorphically related to many other objects (i.e. comments, events, status posts, etc).

In the activities object, I include several fields:

  • User ID (for the person who initiated the action)
  • Target Type (i.e. Comment, Event, Status)
  • Target ID (the ID of the specific model included above)
  • Code for the type of action (which I use to determine how to display it)
  • Date/time of action

I am able to successfully query and display a full feed on the website homepage.

I would like to display a feed on each users page, but it is not so easy. I cannot simple query for all Activity items with User ID = x. The reason being is that certain actions might be related to the user, even though they were not initiated by the user. For example, if someone posts a comment on your pag开发者_JS百科e, the User ID of that Activity will be the other persons, not yours. But I still want to show that action on your page.

In other words, I need to somehow run a query that says: retrieve this Activity item if it was initiated by UserX, or if it is polymorphically linked to an object that is related to UserX.

I've been trying all types of things, but to no avail. There is not much on Google about things like this. Maybe I have gone about this the entirely wrong way? Should I be including all relevant user id's in the Activity object too, even though I am duplicating data? Or is there some sort of query I can run that will be able to handle all the different models that are polymorphically related?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号