2016-12-03 47 views
0

在Rails 4我使用:Rails的:如何使用的has_many塊內部範圍,型號

class Ticket < ActiveRecord::Base 

    has_many :request_attendances, dependent: :destroy 

    has_many :attending_request_attendances, -> { 
    where("data->>'rsvp_completed' = 'true'") 
     .where("data->>'is_coming' = 'true'") 
    }, class_name: 'RequestAttendance' 

end 

在我的門票模型

而且

class RequestAttendance < ActiveRecord::Base 

    belongs_to :tickets, inverse_of: :request_attendances 

    scope :is_coming, -> { where("data->>'is_coming' = 'true'")} 
    scope :rsvp_completed, -> { where("data->>'rsvp_completed' = 'true'")} 

end 

在我RequestAttendance模型

我想做這樣的事

has_many :attending_request_attendances, -> { 
    :is_coming 
    :rsvp_completed 
}, class_name: 'RequestAttendance' 

重用我在RequestAttendance模型中創建的作用域。

是這樣的可能,在它不工作的那一刻,讓我有以下錯誤:

undefined method `except' for :rsvp_completed:Symbol

如果我添加一個地方到的has_many塊這樣的:

has_many :attending_request_attendances, -> { 
    :is_coming 
    :rsvp_completed 
    where("data->>'rsvp_completed' = 'true'") 
}, class_name: 'RequestAttendance' 

它不會出錯,但它也不會使用範圍子句。

+0

你能試試這個:'的has_many:attending_request_attendances, - > {is_coming。 rsvp_completed},class_name:'RequestAttendance'' – Thanh

+0

Thanks @ThanhHuynh this work well。 – alexi2

+0

@ThanhHuynh也許你可以添加它作爲答案,因爲它可能是尋找類似解決方案的其他人的有用模式 – alexi2

回答

2

你可以鏈範圍一起裏面像這樣的聯想:

has_many :attending_request_attendances, -> { 

    is_coming.rsvp_completed 

}, class_name: 'RequestAttendance' 
0

您已經添加了下面的代碼在RequestAttendance模型

scope :is_coming, -> { where("data->>'is_coming' = 'true'")} 
scope :rsvp_completed, -> { where("data->>'rsvp_completed' = 'true'")} 

如果使用下面的代碼在門票模型

class Tickets < ActiveRecord::Base 
    has_many :RequestAttendance 
end 

範圍可供has_many關聯,因此將獲取所有與記錄is_coming'='true'and'data - >>'rsvp_completed'='true'「

您可以使用對象tickets.requestAttendance.is_coming.rsvp_completed

這是你的期望或者如果我誤解請解釋