The data you receive when defining actions in rails
params[:id]
I often expressed it as, but I didn't understand the meaning, so I made a note. I hope it will be helpful for those who are suffering from similar problems.
For example, suppose you want to implement a function to check the details of a post on the screen that displays the post like this. <img width = "798" alt = "Myblog.png " src = "https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/652172/60c1bb16-5d35-51f3-9bdf" -ec24eb3273ee.png "> Since the action to be displayed in detail is a show action, it seems good to define a show action in the controller and prepare a corresponding view.
I think that show actions are often expressed as follows on many rails learning sites.
def show
@post = Post.find(params[:id])
end
This can be decomposed as follows, and each has the following meanings. Post… Post model. Post data stored in the database find… How to get by specifying the one that matches the condition from the Post model params [: id]:… Conditions for data fetched by find params… Data that sticks when you open the URL of a specific tweet : id… id associated with the tweet
In other words, this means that the data corresponding to the id of the post that the user is trying to access will be picked up from the Post model.
@post… Assign the above to an instance variable so that it can be used with external data (or view)
So, by assigning it to an instance variable, it can be displayed in the view file.
When I actually check the routing
post GET /posts/:id(.:format) posts#show
The routing path corresponding to the show action of the posts controller is post /: id. Since this: id corresponds to the post here, I want to display the post with the same id in the view called by the show action. So the show action defines @post and loads it into the view as described above.
Recommended Posts