Create a search window where you can search for model information
■ Improvement of UX ■ Improved understanding of MVC
■ Mac OS catalina ■ Ruby on Rails (5.2.4.2) ■ Virtual Box:6.1 ■ Vagrant: 2.2.7
mac.terminal
$ rails new search
$ rails g model Item name:string text:text price:integer
$ rails g controller items
$ rails g model Order quantity:integer amount:integer item:references
$ rails g conrtroller orders show confirm 
$ rails db:migrate
models/items.rb
has_many :orders
config/routes.rb
root 'items#index'
  resources :items do 
    get 'order' => 'orders#show'
    post 'order/confirm' => 'orders#confirm'
    post 'order' => 'orders#create'
  end
items/index.html.erb
<h2>Item List</h2>
<% @items.each do |item| %>
  <%= item.name %>
  <%= item.text %>
  <%= item.price %>
<% end %>
<h2>Item creation</h2>
<%= form_with modle: @item do |f| %>
  <%= f.text_field :name %>
  <%= f.text_area :text %>
  <%= f.text_field :price%>
  <%= f.submit %>
<% end %>
order/show.html.erb
<h2>Order screen</h2>
<p>Item information</p>
  <%= @item.name %>
  <%= @item.price %>
<%= form_with ([model: @item, @order],local: true url: item_order_confirm_path) do |f| %>
  <%= f.text_field :quantity %> <br>
  <%= f.text_field :amount %> <br>
  <%= f.submit "Send" %> <br>
<% end %>
order/confirm.html.erb
<h2>Order confirmation screen</h2>
  <%= @order.amount %>
  <%= @order.quantity %>
  <%= @item.name %>
  <%= @item.price %>
<%= form_with model:[@item, @order], url:(item_order_path) do |f| %>
  <%= f.hidden_field :amount %>
  <%= f.hidden_field :quantity %>
  <%= f.submit %>
<% end %>
orders_controller.rb
  def show
    @item = Item.find(params[:item_id])
    @order = @item.order.new
  end
  def confirm
    @item = Item.find(params[:item_id])
    @order = @item.order.new(order_params)
  end
  def create
    @item = Item.find(params[:item_id])
    @order = @item.order.new(order_params)
    @order.save
    redirect_to items_path
  end
  private
  def order_params
    params.require(:order)
    .permit(:amount,
            :quantity,
            :item_id)
  end
that's all.
■ About form_with https://qiita.com/tanaka-yu3/items/50f54f5d4f4b8dfe19f3
■ Regarding confirmation screen display https://qiita.com/tomoharutt/items/7959d28764912c64562f
Recommended Posts