Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rails: class methods or scope #37

Open
roman-dubrovsky opened this issue Jul 5, 2019 · 3 comments
Open

Rails: class methods or scope #37

roman-dubrovsky opened this issue Jul 5, 2019 · 3 comments
Labels
feature request New feature or request postponed Not valuable for now

Comments

@roman-dubrovsky
Copy link
Contributor

Just a question: when should we prefer to use rails scope and where class methods?

These are almost similar things ( one different. That if the lambda (or logic) returns nil, scope returns the current value in this, class method returns nil) See https://www.justinweiss.com/articles/should-you-use-scopes-or-class-methods/

Usually, I use the rule. I prefer to use scope for subqueries, but move it to class methods if it needs to use do end block

# ok
def self.active
  where(finished: false)
end

# better 
scope :active, -> { where(finished: false) }

# bad 
scope :active, -> do 
  where(finished: false) 
    .joins(:statuses)
end

# good 
def self.active
  where(finished: false) 
    .joins(:statuses)
end

Your thoughts?

@TheBlackArroVV
Copy link
Contributor

TheBlackArroVV commented Jul 5, 2019

My thoughts about this, that we should use scope for returning some data. Just use a for many lines

(lambda do |user_id|
  Post.where(user_id: user_id)
end)

But as all situation this has a corner case, i think, which i can't specify

@roman-dubrovsky roman-dubrovsky added the feature request New feature or request label Jul 8, 2019
@AleksSenkou
Copy link

AleksSenkou commented Jul 9, 2019

I like scopes for one line and class methods for 1+ lines

For esthetic and readability purposes

@roman-dubrovsky
Copy link
Contributor Author

@TheBlackArroVV in fact, there are no big differences between scopes and class methods which returns an ActiveRecord relation. So here I just agree with Aleks that we should avoid using multiline lamda calls for esthetic and readability purposes

@roman-dubrovsky roman-dubrovsky added the postponed Not valuable for now label Jul 17, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature request New feature or request postponed Not valuable for now
Projects
None yet
Development

No branches or pull requests

3 participants