[Ruby] Rails does it for me automatically, but I was surprised

2 minute read

Make a note of the confusion while learning with TECH::CAMP. I haven’t read the official reference, so it may be wrong in some places.

tl; d

  • You don’t have to write anything in the actions of index, show, new and edit.
  • form_with should be specified by model name and column name.
  • For link_to, you can pass an instance with Prefix.

Rails does it automatically

You don’t need to write anything for index, show, new, edit actions

def index
end

def show
end

def new
end

def edit
end

Of the 7 methods, I am surprised that these 4 will work if I write at least this much. To send data to the view side, I used the Active Record method to declare instance variables, and so on… I didn’t know what I was preparing. Certainly, when these actions are specified by URL or Prefix, it is almost decided to prepare the instance variable of the corresponding model (and id in the case of show and edit). So it means that instance variables are automatically prepared even if you do not write it.

However, if you want to change the display order, read the related model with include to avoid the N+1 problem, link with JavaScript, etc., you need to make appropriate descriptions.

form_with should be specified by model name and column name.

html.erb


<%= form_with(model: @tweet, local: true) do|form| %>
<%= form.text_field :name, placeholder: "name" %>
<%= form.text_area :text, placeholder: "text" , rows: "10" %>
<%= form.submit "SEND" >
<% end %>

It will automatically determine whether the passed instance is in the record, so you do not have to write the path for which action the data is sent. By doing this, it is said that the code of form can be used as it is in the view of new and the view of edit. However, it seems that we need to do a new action to tell form_with that this is an instance of new.

In the part that generates individual input form such as form.text_field :name, if you specify the column name, it will automatically do which column to save. Moreover, when the symbol of this column name is converted to HTML, it is converted like id = "name", so even if you do not set the id for use in JavaScript, you can just use document.getElementById(" It is convenient to specify it with name").

html.erb


<% rooms.each do |room|%>
<%= link_to room.name, room_messages_path(room), method: :get%>
<% end %>

Since Prefix can specify an instance, there is no need to convert it to a numerical value or expand the expression like "rooms/destroy/#{room.id}" one by one. Is it like a constant URI pattern? I was wondering, but who is the Prefix that can specify arguments? Method?