简体   繁体   中英

Rails 3 design: “hiding” an entry with “attribute” true, but only on the api level

In a rails 3 app, I have a model with a boolean attribute called "archived". This attribute is accessible in the cms, where I can go in and edit individual objects, and a checkbox where I can check if an object is archived or not. However, if this object is archived, I don't want this object to be accessible on the api level. That includes the object itself, and its associated objects. At the same time I would like the object to be accessible in the cms, to edit other details and set the archived value back to false, so that I can access the object again in the api and change its behaviour back to default.

I would really appreciate suggestions on how to approach this from a design/high level perspective. Thank you for your help.

When you say "api" do you mean:

  1. Public RESTful API
  2. Access to those models in your own code. Like finder methods on your model?

For the first case, simply get only objects in required state ( Model.where(archived: false) ).

In the second case, taking into account that Ruby is very "open" language, it would be impossible to limit access to any of object property or method. However, to build a public API for other team members to use, you can add methods that correctly filter out your models (look into scope ).

As a second alternative to Model.where(archived: false)

If you used a status enumerator instead of a boolean, you would be able to restrict the list using Model.archived, or Model.published... All you need is an integer field for the model's db table, and something like this in the model:

  enum status: { dev:0, published: 1, archived: 2}

Then in your API, you define what status segment you want to restrict it to as shown above. The enumerator system in RoR is a little tricky to get the hang of at first, but very powerful once you get it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM