It has appeared in both JavaScript and Rails, so I will summarize it. To be precise, the description method and language are Ruby, which only appeared during JS learning.
The translation of render is "give". In other words, the method used to give something. So what do you give? Here, we will introduce three types of usage. What all three have in common is that they are "returning as a response."
With rails, common HTML is put together in one file and called in the form of assignment to the required place. This mechanism is a partial template. The advantage of partial templates is -You don't have to write the same code over and over again. (Reuse) ・ If there is a change, there are few parts to correct. -The amount of description in one file is reduced, making it easier to read. And so on.
How to call
<% render partial: "test" %>
You are calling a file called "_test.html.erb". (If there are files in the same hierarchy)
Use the partial
option to specify the file to call.
local
option, but omit it this time.To perform Ajax (asynchronous communication) using JS, exchange in data format instead of exchanging the server as a file. At that time, Rails is supposed to return the response in the file format by default, so you can change the format by using the render method.
For example, with a controller
def new
post = Post.new
render json: { post: post }
end
It means that we are responding to {post: post}
in json format. Frequent in Ajax.
For example, with a controller in rails
render 'file name'
Then, the specified file can be displayed.
A similar usage is the redirect_to
method, which displays the view via routing or a controller. The difference is that the render
method is displayed directly without going through.
-[x] Value the image of "giving".
-[x] Be careful when using the redirect_to
method properly.
What we can say in common is that they are all returned as responses. There are many other uses, such as just returning a string.