Ruby on rails learning record -2020.10.05

Web form data transmission method GET method : Include in URL `http://example.net?id=3&content=hello`

POST method </ b>: Include in request message article[name]=paiza article[content]=hello+world

If the Rails server logs etc. disappear at the top of the screen, the mouse wheel is useful.

If you cannot operate the wheel Mac: CTRL + Alt + Up / Down arrow keys Windows: CTRL + up and down arrow keys

Rails router function Check the settings of Routes `rails routes` You can check GET and POST

Set router distribution

config/routes.rb


Rails.application.routes.draw do
  get 'welcome/index'

  resources :articles
  root 'welcome#index'
end

welcome # index becomes the top page

View template Helper method : Dedicated command that can be used when creating a view
<%= link_to 'Edit', edit_article_path(@article) %> |
<%= link_to 'Back', articles_path %>

You can write links between pages in your Rails app.

<%= link_to 'text', path %>

This can be converted to the following html.

<a href="path">text</a>

Post form behavior Partial template : Template that describes multiple views To call it, use the render method.
<%= render 'form', article: @article %>

In this case, "_form.html.erb" is the file name of the partial template. You can also use the @article object in the article variable.

Helper method to create form </ b> form_for: Used to create / update a new model like a post form form_tag: Used when not updating Model like search form

form_for method </ b>

<%= form_for(@article) do |f| %>
  <div class="field">
    <%= f.label :name %>
    <%= f.text_field :name %>
  </div>

  <div class="field">
    <%= f.label :content %>
    <%= f.text_field :content %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

Writing controller data Strong parameters : List writable columns for secure database access Describe in article_params method of controller.

articles_controller.rb(part)


# Never trust parameters from the scary internet, only allow the white list through.
def article_params
  params.require(:article).permit(:content, :name, :feeling)
end

Add search form Add search form to view

index.html.erb(part)



<%= form_tag('/articles', method: 'get') do %>
  <%= label_tag(:name_key, 'Search name:') %>
  <%= text_field_tag(:name_key) %>
  <%= submit_tag('Search') %> <%= link_to 'Clear', articles_path %>
<% end %>

<br>

Added search code for index method to controller

articles_controller.rb(part)


# GET /articles
# GET /articles.json
def index
  if params[:name_key]
    @articles = Article.where('name LIKE ?', "%#{params[:name_key]}%")
  else
    @articles = Article.all
  end
end

Recommended Posts