Ruby on Rails - 在 ':include =>' 上添加条件加载有限数量的对象 [英] Ruby on Rails - Add condition on ':include =>' to load limited number of objects

查看:31
本文介绍了Ruby on Rails - 在 ':include =>' 上添加条件加载有限数量的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型用户和事件.基数是一个用户有许多事件.当我查询数据库以提供所有用户及其相应的事件时,它会返回正确的结果.示例语句:Users.find(:all, :include=>[:events])

I have two models User and Event. The cardinality is one User has many Events. When I query the database to give me all the users and their corresponding events it returns the right results. Example statement: Users.find(:all, :include=>[:events])

但是,我需要帮助的是根据条件为用户获取事件.我需要为每个返回的用户只获取今天安排的事件(例如:CREATED_DATE = TODAY).也就是说,我不希望所有事件都与用户关联.就是说,我仍然需要在数据库中找到的所有用户,但是对于今天没有安排事件的一些用户,他们不应该在哈希映射中加载事件.

However, what I need help with is to get events for a user based on a condition. I need for each User returned to get only Events that are scheduled for today (ex: CREATED_DATE = TODAY). That is, I don't want all events associated to Users. Said that, I still need all Users found in the database, but for some of those users that don't have an Event scheduled for today, they should not have an Event loaded in the hash map.

有人可以帮我修改Users.find(:all, :include=>[:events])"Rails 语句,以便我只能获取用户的某些事件,而不是所有事件?

Can someone please help me with modifying "Users.find(:all, :include=>[:events])" Rails statement so I can get only certain Events for Users, not all Events?

谢谢,

推荐答案

据我所知,您不能以您描述的方式使用 :include 选项.

To my knowledge, you can't use the :include option in the way you describe.

无论如何,获取所有事件有什么问题?无论如何,您都必须加载/加入/查询事件表.但是,如果您实例化所有事件,您将需要更多内存.

What is your problem with getting all the events anyway? You will have to load/join/query the events table anyway. You will need more memory, though, if you instanciate all events.

当然,您可以执行两项查询,一项针对具有今天"事件的用户,另一项针对没有事件的用户.

Of course you could do two queries, one for the users with the events "today", and one for those without.

你也可以反过来:

Event.find(:all, :conditions => "...only today...", :include => :user)

这将为您提供今天的所有活动,包括用户.您可以使用另一个查询来获取所有用户而不包括事件,其余的在内存中完成.

Which would give you all events for today with users included. You can use another query to get all users without including the events, and do the rest in memory.

这篇关于Ruby on Rails - 在 ':include =>' 上添加条件加载有限数量的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆