OKADA LABO

ネストの利用例

ネスト利用例

TechReviewSite::Application.routes.draw do
  #get 'products/:product_id/reviews/new' => 'reviews#new'
  #post 'products/:product_id/reviews' => 'reviews#create'
  resources :reviews, only: [:new, :create]

  resources :products, only: :show do
    collection do
      get 'search'
    end
  end
  root 'products#index'

end

の場合のルート

Prefix Verb URI Pattern                Controller#Action
        reviews POST /reviews(.:format)         reviews#create
     new_review GET  /reviews/new(.:format)     reviews#new
search_products GET  /products/search(.:format) products#search
        product GET  /products/:id(.:format)    products#show
           root GET  /                          products#index

これをネスト利用の場合

TechReviewSite::Application.routes.draw do
  #get 'products/:product_id/reviews/new' => 'reviews#new'
  #post 'products/:product_id/reviews' => 'reviews#create'
  #resources :reviews, only: [:new, :create]

  resources :products, only: :show do
    resources :reviews, only: [:new, :create]
    collection do
      get 'search'
    end
  end
  root 'products#index'

end

上記の場合のルート

            Prefix Verb URI Pattern                                 Controller#Action
   product_reviews POST /products/:product_id/reviews(.:format)     reviews#create
new_product_review GET  /products/:product_id/reviews/new(.:format) reviews#new
   search_products GET  /products/search(.:format)                  products#search
           product GET  /products/:id(.:format)                     products#show
              root GET  /                                           products#index

たとえばこれで、new.html.erbにフォームを書く場合の例

<%= form_for [@product, @review] do |f| %>
          
<%= f.label :nickname, style: { 'margin-right' => 8 } %> <%= f.text_field :nickname, placeholder: 'nickname', value: '' %>
<%= f.label :評価, style: { 'margin-right' => 8 } %> <%= f.number_field :rate, placeholder: '評価', value: 1, max: 10, min: 1, html: { class: "search__query", style: 'text-align: right;' } %>
<%= f.text_area :review, placeholder: 'レビューを書いてね!', style: 'width: 100%;height: 300px;' %>
<%= button_tag type: "submit", class: "btn btn--block" do %> 投稿する <% end %>
<% end %>