RoR cz. 4 – dodawanie i edycja

Kontroler

W kontrolerze interesują nas 2 metody dotyczące dodawania nowego autora. Obie wygenerowane automatycznie:

  # GET /authors/new
  def new
    @author = Author.new
  end

Wykonywana przed wyświetleniem formularza.

I druga, wykonywana przy Post:

  # POST /authors
  # POST /authors.json
  def create
    @author = Author.new(author_params)

    respond_to do |format|
      if @author.save
        format.html { redirect_to @author, notice: 'Author was successfully created.' }
        format.json { render :show, status: :created, location: @author }
      else
        format.html { render :new }
        format.json { render json: @author.errors, status: :unprocessable_entity }
      end
    end
  end

Zobaczmy jeszcze metodę prywatną:

  def author_params
    params.require(:author).permit(:name, :surname)
  end

Wskazuje nam ona, które właściwości klasy, są skopiowane z widoku do nowego obiektu. Zapobiega ona „złośliwemu” ustawieniu właściwości ukrytych dla formularza.

Analogicznie, są dwie metody dotyczące edycji:

  # GET /authors/1/edit
  def edit
  end

I druga dla POST:

  # PATCH/PUT /authors/1
  # PATCH/PUT /authors/1.json
  def update
    respond_to do |format|
      if @author.update(author_params)
        format.html { redirect_to @author, notice: 'Author was successfully updated.' }
        format.json { render :show, status: :ok, location: @author }
      else
        format.html { render :edit }
        format.json { render json: @author.errors, status: :unprocessable_entity }
      end
    end
  end

Metoda edit jest pusta, bo mamy w klasie zdefiniowany filtr:

before_action :set_author, only: [:show, :edit, :update, :destroy]

I metodę prywatną:

    # Use callbacks to share common setup or constraints between actions.
    def set_author
      @author = Author.find(params[:id])
    end

Metoda ta jet wywoływana przed każdą metodą wymienioną w filtrze, czyli też przed edit.

Widoki

Automatycznie wygenerowały się widoki i teraz interesują mnie trzy z nich new.html.erb:

<h1>New Author</h1>

<%= render 'form', author: @author %>

<%= link_to 'Back', authors_path %>

Edit.html.erb:

<h1>Editing Author</h1>

<%= render 'form', author: @author %>

<%= link_to 'Show', @author %> |
<%= link_to 'Back', authors_path %>

Bardziej rozbudowany i ciekawy jest _form/html/erb:

<%= form_with(model: author, local: true) do |form| %>
  <% if author.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(author.errors.count, "error") %> prohibited this author from being saved:</h2>

      <ul>
      <% author.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= form.label :name %>
    <%= form.text_field :name, id: :author_name %>
  </div>

  <div class="field">
    <%= form.label :surname %>
    <%= form.text_field :surname, id: :author_surname %>
  </div>

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

Jest to widok częściowy, umieszczony w osobnym pliku, bo używamy go nie tylko przy dodawaniu nowego obiektu, ale też przy edycji.

Widok częściowy może otrzymać parametry. Np. widok new.html.erb przekazuje zmienną: button_name (napis na przycisku submit):

<h3>New author</h3>
<%= render partial: "form", locals: { button_name: "Save new" } %>

a edit.html.erb na:

<h3>Edit author</h3>
<%= render partial: "form", locals: { button_name: "Save changes" } %>

A widok częściowy wygląda jak poniżej. W przedostatniej linijce widzimy wykorzystanie button_name:

<% if @author.errors.present? %>
    <div class="alert alert-danger">
        <p>Errors:</p>
        <ol>
            <% @author.errors.full_messages.each do |message| %>
            <!--<li><%= message.titleize %></li> -->
            <li><%= message %></li>
            <% end %>
        </ol>
    </div>
<% end %>
<%= form_for @author do |f| %>
<div> 
    <%= f.label :name, "Name" %>
    <%= f.text_field :name , class: "form-control "%>
</div>
<div> 
    <%= f.label :name, "Surname" %>
    <%= f.text_field :surname , class: "form-control "%>
</div>
<%= f.submit button_name, class: "btn btn-primary" %>
<% end %>

Widoki korzystają też teraz z bootstrapa.

Dodaj komentarz

Twój adres e-mail nie zostanie opublikowany. Wymagane pola są oznaczone *

Witryna wykorzystuje Akismet, aby ograniczyć spam. Dowiedz się więcej jak przetwarzane są dane komentarzy.