2011-12-13 6 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の場合はfalseと表示されます。

私はどのように私のスコープのものを得るのですか?

答えて

2

という名前のスコープはそうのような製品に直接使用する必要があります。

def index 
    @my_products = current_user.products.my_products 
end 

という名前の範囲には、「製品のリレーションのデフォルトの動作を変更しません。それを使用したいときは、その名前で呼ばなければなりません。

+1

また、「my_products」ではなく「send_data」のようにわかりやすい名前に変更します。現状では、current_user.products.my_productsは冗長に聞こえます。 'current_user.products.send_data'は、取得しようとしているレコードをより正確に表します。 – robotcookies

+0

ありがとう、あなたは良い点を確認します。 – LearningRoR

関連する問題