开发者

Getting the logic out of the view...help with named_scope

I have created an application where I am allowing users to log their Workouts.

The user has the ability to keep a private or public log of their workouts and is denoted by a check_box field that passes the integer 1 to the workout.share column. The private log is viewable through the workouts_controller where I am limiting all output by filtering for current_user.

workouts_controller.rb

@workouts = current_user.Workouts.all

The public workouts are shown through a separate community_controller and there I call the workouts like this

community_controller

@workouts = Workouts.all

and then filtering the results in the view with the following

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

开发者_运维技巧Best I can tell this is not the preferred way to do this and my suspicion is that I want a named_scope such that I can create a new variable `@shared_workouts'. That said I am not familiar with named scopes so could use some help on where to put what and the correct syntax.


If you are using rails 2, use the following:

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

If you are using rails 3, use this instead:

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

Then in the community controller, you could simply use @workouts = Workouts.shared.all


As Peter mentions above, use a named_scope / scope according to the Rails version you use. Also you don't want to use the value 1 for you test. You want to use true (that is if you have used the type boolean in your migration).

The reason is if you change database it may be stored differently (SQLite has a boolean type for example, mySQL uses a tiny int...), and active record will manage it for you. :)

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

Or

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

Then use "Workouts.shared" to access the named_scope.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜