Complex area, rails 3

So, I am creating an application that is appropriate for users. Custom models have 3 attributes (which are relevant to my question anyway: gender:string , looking_for_men:boolean , looking_for_women:boolean .

I currently have a method in my model, for example:

 def browse if self.looking_for_men == true && self.looking_for_women == true if self.sex == "Male" User.where("looking_for_men = ?", true) elsif self.sex == "Female" User.where("looking_for_women = ?", true) end elsif self.sex == "Male" && self.looking_for_men == true User.where("looking_for_men = ? AND sex = ?", true, "Male") elsif self.sex == "Female" && self.looking_for_women == true User.where("looking_for_women = ? AND sex = ?", true, "Female") else if self.sex == "Male" User.where("looking_for_men = ? AND sex = ?", true, "Female") elsif self.sex == "Female" User.where("looking_for_women = ? AND sex = ?", true, "Male") end end end 

This is pretty dirty, as you can tell. Is there anyway to clear this and turn it into a sphere, so let's say, for example, I’m a man-man and I’m looking for women that he returns only women who are looking for men when I make such a request:

 @users = User.all.browse 
+4
source share
2 answers

I would just do the code below to make it more readable. But for some reason I do not quite agree with this decision. Lots more code:

 class User < ActiveRecord::Base scope :male, where(:gender => "Male") scope :female, where(:gender => "Female") scope :looking_for_men, where(:looking_for_men => true) scope :looking_for_women, where(:looking_for_women => true) def browse @women = @men = [] @women = self.interested_females if self.looking_for_women @men = self.interested_males if self.looking_for_men @result = @women.concat(@men) @result.delete(self) #removes the user itself from the result-set return @result end def interested_females return User.female.looking_for_men if self.male? return User.female.looking_for_women if self.female? end def interested_males return User.male.looking_for_men if self.male? return User.male.looking_for_women if self.female? end def male? return (self.gender == "Male") end def female? return (self.gender == "Female") end end 
+5
source

In terms of scope, you can easily move this logic into scope just by passing it to proc.

 class User scope :browse_for, lambda { |user| user.looking_for_men == true && user.looking_for_women == true ... } end @users = User.browse_for(@single_male) 

and you can also combine areas to clear logic: http://edgerails.info/articles/what-s-new-in-edge-rails/2010/02/23/the-skinny-on-scopes-formerly-named- scope / index.html .

I'm not sure if this answers your question?

+1
source

Source: https://habr.com/ru/post/1369330/


All Articles