How is the 'new' action redirected to 'create' in Rails?

前端 未结 3 1511
轮回少年
轮回少年 2021-01-15 21:16

In Rails I can automatically create a set of routes for CRUD actions using resources in the routes file.

This creates index, new

3条回答
  •  长发绾君心
    2021-01-15 21:45

    OOP

    The bottom line answer to your question is that Rails is object orientated (by virtue of being built on top of Ruby). This is very important, as it means everything inside Rails should be based around objects:

    enter image description here

    This leads me to the routes - the resourceful nature of Rails' routes is down to the same idea, that you need to work with objects in your application - hence the resources directive providing 7 key actions to manipulate those objects

    To fully understand Rails, you really need to look into how it works with objects, specifically how they interact with each other


    Redirect

    To answer your question regarding the redirect, the simple answer is that Rails doesn't "redirect" to any action specifically

    Remember, Rails is stateless - it does not persist data through requests - it only has the data which you either initialize at the time, or have sent it

    What you're confused about is how some of the Rails actions seem to be sending your requests to the appropriate "request" action. The answer to this lies in the helpers / methods you use, specifically form_for


    form_for

    form_for builds forms from their ActiveRecord objects.

    Therefore, if you perform the following:

    #app/controllers/your_controller.rb
    Class YourController < ActiveRecord::Base
       def new
          @model = Model.new
       end
    end
    

    This will give Rails the knowledge that it's loading a new object, and therefore will use the form_for method to send the request to the create action

    If you used form_tag, you would not get a redirect to the create action -- that's the magic of Rails -- it's been built to accommodate objects

提交回复
热议问题