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

Move db query logic into models #5

Open
nathanallen opened this issue Jul 22, 2015 · 0 comments
Open

Move db query logic into models #5

nathanallen opened this issue Jul 22, 2015 · 0 comments

Comments

@nathanallen
Copy link

There's a lot going on in politicians_controller.rb:

  • complex queries
  • data filtering
  • api calls

Now that your basic functionality is in place, you're at a really good place to start refactoring. One of the principles of OO design is known as the "single responsibility principle". Right now your controller is doing too much work. Controller should be skinny -- parse the request, gather data for the response/view, -- it should do one thing and one thing well, the glue between the model and the view.

Database queries are perfect for your model, even some basic data filtering is okay there too. You should be able to say things like:

politician.top_contributors({cycle: 2014, limit: 10})
politician.contributions_by_gender(year)
politician.contributions_by_pac(year)
politician.total_raised(year)

Asking a model instance this kind of "question" is perfectly reasonable and will make your controller code a lot cleaner!

That's a good start. But now we have a new problem. Your Politician model knows too much about the world -- it's asking the Contribution database a lot of hard questions, but it's handling all the database queries itself. Ideally we'd be able to ask the Contribution model questions like:

Contibution.top_contributors({politician_id: "123", limit: 10})
Contribution.total({politician_id: "123", cycle: 2014}))

We'll let the Contribution model figure out the details!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant