EnderWiggins
EnderWiggins

Reputation: 390

has_many :condition multiple models how to use join here?

I have the following model structure:

Model Visitor

class Visitor < ActiveRecord::Base
 has_many: triggers 
end

Model Trigger

class Trigger < ActiveRecord::Base
  belongs_to :visitor, :inverse_of => :triggers
  belongs_to :event, :inverse_of => :triggers
end

Model Event

class Event < ActiveRecord::Base
 has_many: triggers 
end

I am trying to setup a custom association in Visitor model like so:

has_many: triggers_that_pass_some_condition ,:class_name => "Trigger", 
 :conditions => ["triggers.some_column >= events.some_column"]

The problem is that it doesn't work .. I am guessing I have to do some kind of join to compare columns of two separate models (that are associated with each other)

I have tried triggers.some_column >= triggers.event.some_column

That does not work either. Anyone has any suggestions? thanks!

Upvotes: 0

Views: 45

Answers (3)

EnderWiggins
EnderWiggins

Reputation: 390

Thanks to the clue from Darpa, I eventually settled on this:

 has_many :custom_trigger, {:class_name => "Trigger", :include => :event,
 :conditions => ["triggers.some_column >= events.another_column"]}

Upvotes: 0

Collin Graves
Collin Graves

Reputation: 2267

Make sure you first add the correct association between Visitor and Trigger in your model setup. From there, you can add a custom association as follows:

class Visitor < ActiveRecord::Base
  has_many :approved_triggers, -> { includes(:events).where("events.something = ?", true).references(:events) }, class_name: 'Trigger', inverse_of: :visitor
end

class Trigger < ActiveRecord::Base
  belongs_to :visitor, inverse_of :triggers
end

Right now your Trigger class holds no association to a Visitor.

Upvotes: 1

Darpa
Darpa

Reputation: 406

Try the following code..

class Trigger < ActiveRecord::Base
  belongs_to :event 
  belongs_to :visitor
end

# Visitors.rb
has_many :triggers_with_condition, -> { includes(:event).where(some_trigger_column >= event.some_event_column)}, class_name: "Trigger"

Upvotes: 1

Related Questions