[英]Rails has_many complicated query
I'm not quite sure how to word this but I'll give it a shot. 我不太确定该如何措辞,但我会试一试。
Basically I have two models: Message and Event. 基本上,我有两个模型:消息和事件。
Message belongs_to event and event has_many messages. 消息belongs_to事件和事件has_many消息。
When I call something like: 当我打这样的电话:
Event.first.messages
It produces this output: 它产生以下输出:
SELECT "messages".* FROM "messages" WHERE "messages"."event_id" = 1
What I would like to be able to do is keep the association between the two, but add another column into the has_many equation so the SQL produced is something like: 我想做的是保持两者之间的关联,但是在has_many方程中添加另一列,以便生成的SQL类似于:
SELECT "messages".* FROM "messages" WHERE "messages"."event_id" = 1 OR "messages"."type_id" = 4
Where both the Message and Event tables contain a type_id column. Message和Event表都包含type_id列。
Is this possible? 这可能吗?
You can't make pure ActiveRecord OR queries 您不能进行纯ActiveRecord或查询
Other ways to solve this 解决此问题的其他方法
Use SQL string as where argument: 使用SQL字符串作为where参数:
Message.where("event_id = ? or type_id = ?", Event.first.id, 4)
Make 2 queries and then you add them: 进行2个查询,然后添加它们:
event_messages = Event.first.messages
type_messages = Message.where(:type_id => 4)
all_messages = event_messages + type_messages
Raw SQL: 原始SQL:
How to execute a raw update sql with dynamic binding in rails 如何在Rails中使用动态绑定执行原始更新SQL
Yes its possible By Using 是的,可以通过使用
Event.first.messages.where(:type_id => 4)
Try it 试试吧
尝试这个
Event.first.find(:all, :conditions => ["where type_id = ? or event_id = ?", 4, 1])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.