min117の日記

初期desireもち。趣味Mac,メインFedora,仕事xp。

ChatCPT「テニスラケットのガットの張りをメモして管理するWebアプリのサンプルコードを示して」

ハピタス登録で1,000円分になるURL

その買うを、もっとハッピーに。|ハピタス

 

Ruby on Railsアプリ

ほんとに動くか近いうちに試す。

 

# In the controller
class RacketController < ApplicationController
  def index
    @rackets = Racket.all
  end

  def new
    @racket = Racket.new
  end

  def create
    @racket = Racket.new(racket_params)
    if @racket.save
      redirect_to rackets_path
    else
      render :new
    end
  end

  private

  def racket_params
    params.require(:racket).permit(:name, :tension)
  end
end

# In the model
class Racket < ApplicationRecord
  validates :name, presence: true
  validates :tension, numericality: { greater_than: 0 }
end

# In the view (new.html.erb)
<h1>New Racket</h1>
<%= form_for @racket do |f| %>
  <% if @racket.errors.any? %>
    <div class="error_messages">
      <h2>Form is invalid</h2>
      <ul>
        <% @racket.errors.full_messages.each do |message| %>
          <li><%= message %></li>
        <% end %>
      </ul>
    </div>
  <% end %>
  <p>
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </p>
  <p>
    <%= f.label :tension %><br>
    <%= f.number_field :tension %>
  </p>
  <p>
    <%= f.submit %>
  </p>
<% end %>

# In the view (index.html.erb)
<h1>Listing Rackets</h1>
<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Tension</th>
    </tr>
  </thead>
  <tbody>
    <% @rackets.each do |racket| %>
      <tr>
        <td><%= racket.name %></td>
        <td><%= racket.tension %></td>
      </tr>
    <% end %>
  </tbody>
</table>

 

 

 

 

その買うを、もっとハッピーに。|ハピタス