如何根据条件在rails中预加载关联

时间:2016-11-09 05:05:43

标签: ruby-on-rails ruby postgresql activerecord

我正在尝试预加载关联,例如您有function addToArr(elem){ //If the element does not have 'addedToArr' defined, //or the value of 'addedToArr' is not 'false' (which makes the condition true) if (!elem.addedToArr){ arr.push(elem.id); //Push the element's id into array elem.addedToArr = true; //Set 'addedToArr' of the element to true } alert(arr.length); //This will alert the new length of the array } grid = [[0,0,0,4],[0,0,4,2],[2,4,4,2],[0,8,4,2]] [(i,j) for i,b in enumerate(grid) for j,a in enumerate(b) if a==0] Out[81]: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (3, 0)]

我想预加载当前用户为Posts的所有帖子,但同时也预加载所有subscribers

我使用的查询是这样的:

subscriber

这为我提供了subscribers的正确列表,但并没有为每个Post.includes(:subscribers) .references(:subscribers) .where(subscribers: { id: current_user.id }) 提供posts,仅为当前用户。有没有办法获得所有subscribers,同时将其范围限定为我可以看作订阅者的帖子?

1 个答案:

答案 0 :(得分:1)

试试这个

Post.includes(:subscribers).where(id: Post.joins(:subscribers).where(subscribers: {id: current_user.id}).select(:id))