可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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...
回答1:
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.
回答2:
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!
回答3:
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.
回答4:
open your model folder, that is a hint of what resources you have! example: users, pictures, comments...