2015-11-19 33 views
0

以下是我的結構:在導軌範圍內製作一個環路

具有與目標模型(destination_id)的belongs_to關聯的別墅模型。

具有與目的地模型的habtm關聯的用戶模型。

在我的索引視圖今天,我用:

<% current_user.destinations.each do |destination| %> 
    <% @villas.each do |villa| %> 
    <% if destination == villa.destination %> 
     <%= villa.name %> 
    <%end%> 
    <%end%> 
    <%end%> 

這不是很清楚,這樣我就可以成爲一種範圍在我的別墅模型選擇別墅,其中目標ID == current_user.destinations?

非常感謝

回答

1

你爲什麼不列出從目的地本身的兒童別墅?

<% current_user.destinations.each do |destination| %> 
    <% destination.villas.each do |villa| %> 
    <%= villa.name %> 
    <%end%> 
<%end%> 

如果你想放棄這個內置的功能,或者如果你再從你的@villas關係作用域查詢,這裏是你怎麼做範圍as per these docs

class Villa < ActiveRecord::Base 
    # ... 
    scope :by_destinations, -> (destinations) { where(destination: destinations) } 

    # alternatively... 
    def self.by_destinations(destinations) 
    where(destination: destinations) 
    end 
end 

然後參考它與

<% @villas.by_destinations(current_user.destinations) do |villa| %> 
    <%= villa.name %> 
<%end%>