开发者

How do I filter through an associated resource column using a named_scope?

开发者 https://www.devze.com 2023-01-31 00:25 出处:网络
I have built a Ruby on Rails application that allows users to track their workouts. User has_many :workouts

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
0

精彩评论

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