Do you know what the difference between redirect and render is? If you are a Rails beginner, you may not understand it, so I will explain it briefly.
The difference is ** whether it goes through the controller **. I will write the flow of each process.
■ redirect Send request → Identify controllers and actions by routing → The action in the specified controller operates → The view file corresponding to the action that was performed is displayed as a response.
■ render Show specified view file
As an example that you often see, when you save the posted data, you can use redirect if the saving is successful and render if it fails. Let me explain a little with a code example.
def new @post = Post.new end def create @post = Post.new(post_params) if @post.save redirect_to root_path else render "new" end end
Let's see the actual movement in the video This time, we have validated it so that it cannot be saved unless you enter 5 or more characters.
You can easily understand that when the data is saved successfully, you just move to the root path (posted data list). If the save fails, render will read the new view file directly. At this time, since it does not go through the controller, the instance variable (@post) passed to the view file is not the one used in the new action, but the one used in the ** create action ** (post data is stored). By doing this, when the new view file is displayed after the save fails, it will ** retain the input data **. If you use redirect when saving fails, the new action will be loaded and @post will be passed a newly created empty instance, so the data you entered will be lost.
In addition to this usage, render is a very convenient method that can be used as a partial template or for iterative processing. If you can use it well, you will enjoy coding, so it's a good idea to remember it.
Thank you for watching until the end!