1

I'm a bit stuck with something that I've previously done countless times in Node or Django.

I'm building an API-only Rails app.

Say I have a Post model containing blog posts. The model has a published attribute, which determines if a certain post is available already to the larger public.

Obviously, the goal in the controller is to return the JSON of the post(s) if the flag is true.

For collections, I have created a simple scope in my Post model as follows:

  scope :published, -> { where(published: true) }

However, for single requests I am not sure what is the correct, or rather: the Rails way of handling this. I can "force it out", but I feel like there's a neat "convention over configuration" trick for things like this.

In essence, I'm curious about the cleanest solution for this: if the post's published attribute is true, return the post object, if it's false, return a 404

Should I look at scopes? Serializers? Where is the treasure hidden?

Thanks for contributing!

zcserei
  • 577
  • 7
  • 30

1 Answers1

3

No golden bullet, but going with scopes is fine.

In your controller you probably have something similar to this:

post = Post.find(params[:post_id])

Now, using your published scope will work as expected (its kind of/results in an SQL AND):

post = Post.published.find params[:post_id]

It will not first query all published Posts from the database and then look through them. The beauty of the specific ORM (doing code object <-> database mappings) here is that you will end up with a single query against your database (as can be seen in the log files).

Returning the 404 or whatever is than still up to you/your controllers business - as find will raise an exception if nothing is found it defaults to the behavior you wished.

Felix
  • 4,510
  • 2
  • 31
  • 46