I have built a Ruby on Rails application that allows users to track their workouts.
User has_many :workouts
Workout belongs_to :user
I am attempting to call only workouts from male users. How do I开发者_如何学编程 write a named scope for Workout.rb
to call only workouts from male users?
In my case, the user.sex column is a string that collects either Male
or Female
.
I am using rails 2.3.8 for this particular application.
Try this:
class Workout
belongs_to :user
named_scope :all_male, :joins => :user,
:conditions => ["users.sex = ?", "Male"]
named_scope :all_female, :joins => :user,
:conditions => ["users.sex = ?", "Female"]
end
Now you can use the scope as:
Workout.all_male
Workout.all_female
精彩评论