2010-11-19 69 views
1

我創建了一個應用程序,允許用戶記錄他們的鍛鍊。獲取邏輯視圖...幫助named_scope

用戶可以保留其鍛鍊的私人或公共日誌,並由check_box字段表示,該字段將整數1傳遞給workout.share列。私人日誌可以通過workouts_controller查看,我通過過濾current_user來限制所有輸出。

workouts_controller.rb

@workouts = current_user.Workouts.all 

公共鍛鍊通過單獨community_controller示出並有我稱這樣

community_controller的鍛鍊

@workouts = Workouts.all 

然後過濾在結果查看以下內容

<% @workouts.each do |workout| %> 
<% if workout.share == 1 %> 
    ... 
<% end %> 
<% end %> 

最好我可以告訴這不是這樣做的首選方法,我懷疑是我想要一個named_scope,以便我可以創建一個新變量`@shared_workouts'。這就是說我不熟悉命名範圍,所以可以在哪裏放置什麼和正確的語法使用一些幫助。

+0

什麼版本的Rails? – 2010-11-19 02:31:38

回答

1

如果使用的是軌道2,使用以下方法:在社區控制器

class Workout < ActiveRecord::Base 
    scope :shared, where(:share => 1) 
end 

然後,你可以簡單地使用:如果您使用的是軌道3

class Workout < ActiveRecord::Base 
    named_scope :shared, :conditions => {:share => 1} 
end 

,改用此@workouts = Workouts.shared.all

1

彼得上面提到的,使用根據您使用Rails的版本named_scope /範圍。你也不想爲你測試使用值1。你想要使用true(就是說,如果你在遷移中使用了布爾類型)。

的原因是,如果你改變數據庫可以存儲不同(SQLite的有一個布爾類型,例如,MySQL使用一個微小的INT ...),和活動記錄將管理它。 :)

class Workout < ActiveRecord::Base 
    named_scope :shared, :conditions => {:share => true} 
end 

或者

class Workout < ActiveRecord::Base 
    scope :shared, where(:share => true) 
end 

然後使用 「Workouts.shared」 訪問named_scope。