0

i have this query, which I want to se in rails way. Could please anyone help me here?

select * from users
  ,buyer_events
  ,supplier_events
where (users.id = buyer_events.buyer_id
      or users.id = supplier_events.supplier_id)
      and supplier_events.event_id = 11
      and buyer_events.event_id = 11;

PostgreSQL

If more information is needed just write in comments :)

3
  • do you have to select all users which match the where cond? Commented Jan 20, 2015 at 12:46
  • @МалъСкрылевъ He is selecting all columns from table users, not all users. Commented Jan 20, 2015 at 12:48
  • have you the two separate tables: buyer_events, and supplier_events? Commented Jan 20, 2015 at 12:50

2 Answers 2

1

I guess it should be something like this:

class User
  has_many :supplier_events
  has_many :buyer_events

  scope :with_event, ->(event_id) {
    joins(:supplier_events, :buyer_events).merge(supplier_events.for_event(event_id)).merge(buyer_events.for_event(event_id))
  }
end

class SupplierEvent
   belongs_to :supplier, class_name: :User
   belongs_to :event, class_name: :Event

   scope :for_event, ->(event_id) { where(event_id: event_id) }
end

class BuyerEvent
   belongs_to :buyer, class_name: :User
   belongs_to :event, class_name: :Event

   scope :for_event, ->(event_id) { where(event_id: event_id) }
end

Then issue:

User.with_event(11)
Sign up to request clarification or add additional context in comments.

Comments

0
class User < ActiveRecord::Base
  ...
  def self.buyers_and_suppliers user_id
    joins(:buyer_events, :supplier_events).where(users: {id: user_id}, supplier_events: {event_id: 11}, buyer_events: {event_id: 11})
  end
  ...
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.