has_many:条件多个模型如何在这里使用join?

时间:2015-06-24 19:58:51

标签: sql ruby-on-rails join activerecord associations

我有以下模型结构:

模特访客

class Visitor < ActiveRecord::Base
 has_many: triggers 
end

模型触发

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

模型事件

class Event < ActiveRecord::Base
 has_many: triggers 
end

我正在尝试在访问者模型中设置自定义关联,如下所示:

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

问题是它不起作用..我猜我必须做某种连接来比较两个独立模型的列(彼此相关)

我试过了 triggers.some_column&gt; = triggers.event.some_column

这也不起作用。有人有什么建议吗?谢谢!

3 个答案:

答案 0 :(得分:1)

确保首先在模型设置中添加Triggerclass 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 之间的正确关联。从那里,您可以添加自定义关联,如下所示:

Trigger

现在,您的Visitor班级与NSMutableDictionary *configuration = [[NSMutableDictionary alloc] init]; 没有任何关联。

答案 1 :(得分:1)

请尝试以下代码..

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"

答案 2 :(得分:0)

感谢Darpa的线索,我最终确定了这一点:

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