2014-09-24 76 views
0

我有3种型号在我的Ruby on Rails的4应用程序,就像这样:如何在rails 4中的has_many上执行嵌套条件?

user has_many orders 
order_line belongs to order 

在ORDER_LINES模式,我有一个完成标志。

在我的用户模型中,如何才能使条件只获取订单,订单行还没有完成?

我有这样的事情在我的用户模型的尝试:

has_many :orders, -> { include :order_lines, where :order_lines => { is_completed: false } } 

如果在尝试上述我得到的错误:

syntax error, unexpected tSYMBEG, expecting keyword_do or '{' or '(' 

回答

0

要传递的选项includes,而不是include 也没有方法链发生。

尝试以下

has_many :orders, -> { includes(:order_lines).where(:order_lines => { is_completed: false }) } 
+0

我试过了,但得到了:尝试使用时出现错误:错误:缺少表order_lines的FROM-clause条目。我不知道是否因为我在我的order_lines模型中设置了self.table_name ='ord_lines'? – Dofs 2014-09-25 05:46:04

0

我觉得更清洁的方法是在命令模式添加范围。下面的代码可能为你工作,

class User < ActiveRecord::Base 
    has_many :orders 
end 

class Order < ActiveRecord::Base 
    belongs_to :user 
    has_many :lines 

    scope :incomplete, -> { 
     includes(:lines). 
     where("lines.is_completed = ?", false). 
     references(:lines) 
    } 
end 

class Line < ActiveRecord::Base 
    belongs_to :order 
end 

和呼叫让用户不完全的订单,

user = User.first 
user.orders.incomplete 

而且,我认为这是更好,如果列的名称或者是状态:字符串或完成:布尔代替is_complete。

+0

在这种情况下,我从不想要完成订单,否则我会同意你的意见。但是,尝试使用时出现错误:错误:缺少表order_lines的FROM-clause条目。 – Dofs 2014-09-25 05:45:19