0

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.

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:

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.

Is this possible?

jay
  • 305
  • 1
  • 3
  • 12

3 Answers3

1

You can't make pure ActiveRecord OR queries

Other ways to solve this

Use SQL string as where argument:

Message.where("event_id = ? or type_id = ?", Event.first.id, 4)

Make 2 queries and then you add them:

event_messages = Event.first.messages
type_messages = Message.where(:type_id => 4)
all_messages = event_messages + type_messages

Raw SQL:

How to execute a raw update sql with dynamic binding in rails

Community
  • 1
  • 1
Agush
  • 5,036
  • 1
  • 19
  • 32
0

Yes its possible By Using

Event.first.messages.where(:type_id => 4)

Try it

Babasaheb Gosavi
  • 7,735
  • 1
  • 14
  • 14
  • 1
    This would create an AND clause, whereby the question is about an OR. As far as I understand, OP wants to see all messages that are either directly associated by ID or have type_id = 4 (and ignore event_id in this case) – thorsten müller Jan 15 '13 at 11:03
  • Correct, ignore the event_id if there is a matching type_id. – jay Jan 15 '13 at 16:10
0

try this

Event.first.find(:all, :conditions => ["where type_id = ? or event_id = ?", 4, 1])
Dnyan Waychal
  • 1,418
  • 11
  • 27