It was given by render

Introduction

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.

What is the render method?

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."

Give partial template </ font>

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.

Partial template points

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.

  • The file name starts with "_ (underscore)".
  • When using variables in a partial template, use the local option, but omit it this time.

Specify the response format </ font> and give

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.

Point of specifying the response format

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.

Give view </ font>

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.

point

-[x] Value the image of "giving". -[x] Be careful when using the redirect_to method properly.

Finally

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.