2011-12-13 62 views
0

我在Product模型中定義的範圍是:查看是不是基於範圍?

class Product < ActiveRecord::Base 
    attr_accessible :send_to_data # this is a boolean column 
    scope :my_products, where(:send_to_data => true) 
end 

然後在我的控制器:

class ProductsController < ApplicationController 
    def index 
    @my_products = current_user.products 
    end 
end 

最後我的觀點:

<% for product in @my_products %> 
    <%= product.user_id %> 
    <%= product.name %> 
    <%= product.send_to_data %> 
<% end %> 

但它仍然呈現的所有產品,包括那些被標記爲:send_to_data的錯誤。

我如何獲得我的範圍只?

回答

2

命名的範圍有直接使用在產品上,像這樣:

def index 
    @my_products = current_user.products.my_products 
end 

命名的範圍不改變「產品」的關係的默認行爲。當你想使用它的時候,它的名字必須被叫做它的名字。

+1

我也會將它重命名爲更類似於'send_data'而非'my_products'的描述。實際上,current_user.products.my_products聽起來多餘。 'current_user.products.send_data'可以更好地瞭解您試圖獲取的記錄。 – robotcookies 2011-12-14 00:18:14