Restful URI from Rails Tutorial Demo app - ruby-on-rails

From the originall rail tutorial: http://ruby.railstutorial.org/chapters/a-demo-app#sec-a_user_tour
URIs designed as followings
/microposts
/microposts/1
Now consider if you want to organize each micropost into exactly ONE categorie (name is unique), what URI you will perfer?
/categories
/categories/123
/categories/jewelries
/categories/123/jewelries
/categories/jewelries/123
or singular counterparts
/categories
/categories/123
/categories/jewelry
/categories/123/jewelry
/categories/jewelry/123

Naming ReST resources is mostly a matter of taste. Just keep them coherent. If you choose to name /categories to serve a list of category, choose /jewelries to serve a list of jewelry.
I prefer using singular, /category for a list of category, /category/123 for one category. You can use singular or plural as long as every resource follow the same rule.

Related

How to name RESTFUL resources in this case

I am developing a petitions site that is using RESTFul techniques.
For example: /petition/1 indentifies a certain petiton (resource).
How should I name
a) Signing a petition?
/petition/sign/1
or
/petition/1/sign
or
???
b) Searching for a petition based on terms (rich, for example)
/petition/search/rich
/petition?search=rich
And lastly
c) Seeing only a certain category
/petition/category/1
/petition?category=1
Thank you.
As #BrianDriscoll mentioned in his comment, when creating the URLs for resources in a REST architecture, you have to be careful to keep the URLs to being just the nouns (the things in your application) and the verbs are the HTTP methods.
Now that that little bit is out of the way, we can start to dig in to what the nouns in your application really are. From the looks of it, you have essentially 3 "things" (or nouns) in your domain:
Petitions
Petition Signatures
Petition Categories
Assuming that a Petition Signature can only ever be applied to one petition, I would expect the following URL patterns to represent your resources:
/petitions - A list of all petitions (the petition root)
/petitions/5 - A single petition
/petitions/5/signatures - A list of all signatures for a single petition
/petitions/5/signatures/7 - A single signature on a single petition
/categories - A list of all the categories (the category root)
/categories/3 - A single category (which is probably a list of all petitions in the category)
Then, with these resources, you can use the HTTP verbs to manipulate the resources:
POST /petitions - Create a new petition
POST /petitions/9/signatures - Create a new signature on the petition
etc.
Lastly, for searching, you would simply pass a query string to your /petititions URL like so:
GET /petitions?query=blah
The query can be whatever you need for the search engine and it should return a list of petitions that match that query. The same holds true for searching on signatures within a petition or petitions within a category.
This should be enough to get you up and running for now. Ultimately, it comes down to deciding on what "things" and representations of those things your application needs, and then the URLs are just the "names" of those things, much like an address is the "name" of a house. Interacting with those resources (things) is done through the different HTTP verbs.
This is only scratching the surface of the true power of a REST architecture, which includes things like defining content types so that clients know how to navigate your domain, and using hypertext as the engine of application state so that clients can actually do the navigation on a server.
I would do
POST to /petitions/1/signatures
GET to /petitions?query=rich
GET to /categories/1/petitions (assuming you want a list of petitions in a category)
For rails routes it would be:
resources :categories do
resources :petitions
end
resources :petitions do
resources :signatures
end

What is a "resource" in Rails?

Dumb question but I have some lingering confusion of what, exactly, a "resource" is in Rails. The term is used everywhere but I get a funny feeling it might be being used rather loosely. It's referenced in the model, the controller and, quite literally, in routes.rb.
Is it the specific route? For example, map.resources maps the 7 RESTful "resources". So an example of one resource would be the call to, say, the index action of a particular class's controller?!?
Is it a reference to the whole page/object being retrieved? or perhaps, more narrowly, a database table? or the row being retreived?
Is it something else?
Anyway, hopefully someone can set me straight...
Any object that you want users to be able to access via URI and perform CRUD (or some subset thereof) operations on can be thought of as a resource. In the Rails sense, it is generally a database table which is represented by a model, and acted on through a controller.
For example, you might have a User resource (with a users table in your DB). This is represented by a User model, is mapped to users_controller with map.resources :users (which then generates routes like /users (a collection of User resources) and /users/1 (a specific User resource).
You act upon those resources by using the appropriate HTTP method when making calls to those resources. POST to the resource collection (/users) creates a new record; GET retrieves a list of resources (/users) or a specific user (/users/1). PUT updates a specific user (/users/1/), and DELETE destroys that user. The URLs are the same, but the result (and controller action) may be different based on the HTTP verb. The idea, though is that /users/1 always means "I'm interacting with the User that has ID #1", regardless of the action.
Here's a good article discussing how most developers think that "Resource" is synonomous with the database table, the argument, I guess, being that mapping to the resource is mapping the controller to that database table (or, with ActiveResource, to another REST url).
Basically, I think a "resource" is "persisted data." map.resources maps the 7 RESTful actions to a particular suite of persisted data.
But I haven't thought about it too much in depth. Good question!
I think they probably mean it in the general web sense, i.e., Resource (Web):
the referent of any Uniform Resource Identifier
I don't think it has anything to do with database tables.
open your model folder, that is a hint of what resources you have!
example: users, pictures, comments...
A lot of people here say that resources refer to the database tables you have. It might be true sometimes but not necessarily true always. I could give you a lot of examples where you don't have a corresponding table in your database for a particular resource. Hence asssociating it with tables is rather wrong.
I would define a resource as a route which maps to related requests. So instead of declaring separate routes for the actions you want to do you can simply declare them using a resourceful route.In Rails, a resourceful route provides a mapping between HTTP requests and URLs to controller actions.
So say you define resources :users in config/routes.rb. You can now use a number of helpers to the controllers in your application like edit_user_path which returns users/edit .
Here's a good link: https://api.rubyonrails.org/v5.2.1/classes/ActionDispatch/Routing/Mapper/Resources.html
Which basically says: Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index, show, new, edit, create, update and destroy actions, a resourceful route declares them in a single line of code:
resources :photos

Why does Rails use plurals for new and create?

I understand why a Rails index method would use the plural form of a resource - we're showing all projects, for example.
And I understand why the show method would use the singular form - we only want to see one project, with a particular ID.
But I don't understand why new and create would use the plural. Is there a way to create more than one project at a time? Is there some other reasoning for using the plural here that someone could explain?
New and Create aren't plural, in the way I think about REST. Instead, I think about it like:
whatever.com is your base domain, and whatever.com/books means that you have a collection of resources each named book. The collection itself is named books.
So, when you want to create a new book, you are asking the collection for the information needed to create a new book. This becomes /books/new
When you actually create the book, you are posting information to /books. The HTTP verb is POST, so when you POST to your collection, you execute the create action.
This looks like a good starting point on REST.
I thought they were always plural. Scroll down a bit on this page for an example of the routes generated by resources :photos
Whether you're GETting a single resource or POSTing to the collection, you're still in the domain of photos. So, search the domain of photos given an id, POST a new photo to the domain of photos, etc.

Ruby on Rails - differentiating plural vs singular resource in a REST API

I'm working on building the URLs for my REST API before I begin writing any code. Rails REST magic is fantastic, but I'm slightly bothered the formatting of a URL such as:
http://myproject/projects/5
where Project is my resource and 5 is the project_id. I think if a user is looking to retrieve all of their projects, then a respective HTTP GET http://myproject/projects makes sense. However if they're looking to retrieve information on a singular resource, such as a project, then it makes sense to have http://myproject/project/5 vs http://myproject/projects/5. Is it best to avoid this headache, or do some of you share a similar concern and even better - have a working solution?
Rails (3) has a lot of conventions when it comes to singular vs plural. For example, model classes are always singular (Person), while the corresponding tables are always plural (people). (For example, Person.all maps to select * from people.)
For routes, there's a concept of a singular resource as well as a plural resource. So if you did resource :account then you would get paths like /account for the default path or /account/edit for a path to a form to edit the account. (Note that Rails uses /account with a PUT method to actually update the account. /account/edit is a form to edit the account, which is a separate resource from the account itself.) If you did resources :people, however, then you would get paths like /people, /people/1, and /people/1/edit. The paths themselves indicate whether there can only be one instance of a given type of resource, or whether there can be multiple instances distinguished by some type of identifier.
I agree, go with the flow. Consider how the URL forms a hierarchy.
The root of your website is where you start to access anything.
/projects/ narrows it down to only projects, not anything else. From projects you can do lots of things, /list, /index/, /export, etc... the /id limits things even further.
At each / the scope of what do becomes narrower, and I think it makes sense.
Further programming is all about arbitrary rules. Indexs starting at 1 vs 0, and so on. Anyone working with your urls will sort things out in short order.
There are cases where a singular path to a resource is helpful. If your resource ids are non-numeric user defined names then routing clashes are possible. Example:
/applications/new --> create a new application or show user's application named new?
In this situation you can choose to limit the user input to avoid the clash, or, this can be worked around by overwriting the default Rails 3 behavior:
class ActionDispatch::Routing::Mapper
module Resources
RESOURCE_OPTIONS << :singular_resource
class Resource
def member_scope
#options[:singular_resource] ? "#{singular}/:id" : "#{path}/:id"
end
def nested_scope
#options[:singular_resource] ? "#{singular}/:#{singular}_id" : "#{path}/:#{singular}_id"
end
end
end
end
Then when specifying a new resource route:
resources :applications, :singular_resource => true
Which will generate the routes:
GET /applications
GET /applications/new
POST /applications
GET /application/:id
GET /application/:id/edit
PUT /application/:id
DELETE /application/:id

Singular or plural controller and helper names in Rails

Is there any disadvantage to using singular names for controllers and helpers? Nothing seems to rely on this. It even seems helpers don't have to make the same choice about singular vs. plural as their corresponding controllers, at least according to my limited experimentation. Is that true?
Definitely plural.
With restful routing and a singular controller
Controller:
dog_controller.rb
Routes:
map.resources :dogs # => blows up
map.resources :dog # is ok, but...
dogs_path # => blows up
dog_path # => ok
Using a plural controller
Controller:
dogs_controller.rb
Routes:
map.resources :dogs
dogs_path # => ok
dog_path # => ok
rails generate controller --help has plural examples:
Example:
`rails generate controller CreditCards open debit credit close`
CreditCards controller with URLs like /credit_cards/debit.
Controller: app/controllers/credit_cards_controller.rb
Test: test/controllers/credit_cards_controller_test.rb
Views: app/views/credit_cards/debit.html.erb [...]
Helper: app/helpers/credit_cards_helper.rb
Using plural names for controllers is just a convention.
Plural names usually sound more natural (especially for controllers that are tied directly to a specific model: User -> Users, etc.), but you can use whatever you want.
As for helpers, all helpers are available for all controllers by default, so technically, how you name your helpers doesn't matter at all. It's just another convention to keep a controller's helper functions in a helper with the same name as the controller.
A Model is singular because it references a single object like User. A controller is plural because it is the controls (methods) for the collection of Users. How one names the routes is all up to that individual developer. I've never had a user complain that a URL for a web request is singular or plural. The end result to maintain a common convention for current and future contributors while serving quality page displays or the API requests for the end users.
You have a very complete explanation in the Rails guides:
http://edgeguides.rubyonrails.org/routing.html#resource-routing-the-rails-default
It is the Rails convention that one controller handles one model, whether one or more instances of that model can exist during runtime. However, you can have a Rails application where (some of) the controllers (and the associated views) are not associated with any particular model, but rather handle a more complex set of functionality. In this case, the automatic pluralization doesn't make any sense.
The Rails application I'm currently working on fits into this category, and it's simply an irritation to me that Rails expects that the identifiers I define as a singular in one place are then used in their plural forms in other places. For example, I might want to define something like this in config/routes.rb:
resource :dashboard, :only => [:show]
and then I want a controller DashboardController to display summary information about certain aspects of the application, gathering information from more than one database table. So here, Dashboard does not refer to any model of the application, and it would be just weird to have the controller's name be DashboardsController.
I found a good solution to the irritation of automatic pluralization in this answer. In short, edit file config/initializers/inflections.rb and add the words you don't want to be automatically pluralized to this definition:
ActiveSupport::Inflector.inflections do |inflect|
inflect.uncountable %w( dashboard foo bar baz )
end
If the controller is a resource then it must be plural...
For example
Controller
articles_controller.rb
Model
article.rb
But you can use singular controller names when you do not have corresponding models like
welcome_controller.rb
The naming convention of controllers in Rails favors pluralization of the last word in the controller's name, although it is not strictly required (e.g. ApplicationController).
For example, ClientsController is preferable to ClientController, SiteAdminsController is preferable to SiteAdminController or SitesAdminsController, and so on.
Following this convention will allow you to use the default route generators (e.g. resources, etc) without needing to qualify each :path or :controller, and will keep URL and path helpers' usage consistent throughout your application.
Ref: Controller Naming Convention-Rails Doc
I feel better when I use singular for Controller name
Using plurals just sounds better, and then if you have a controller that handles a singular resourse, ie user, then you can still name the url /user.
With helpers there is often no need to have a helper for every controller, and often there will be helper methods you can use ascorss multiple controllers and rather litter them all through your application helper you could put them in custom helpers instead like eg layout_helper or any other well named file.

Resources