コンテンツを追加・編集・削除する画面を作っています。
はじめて質問します。
現在Rails5でウェブサイトのコンテンツの追加・編集・削除を一つの管理画面で一括管理できるものを作っています。
管理画面にはコンテンツの数だけテキストエリア内にコンテンツ内容が表示されていて、テキストエリアのそばに送信・削除ボタンが存在していて、テキストエリアの内容を編集して送信すると更新されるというものを考えています。
現在、新規コンテンツの追加と既存コンテンツの削除まではできましたが、編集がうまくいきません。
以下にソースコードを示します。
static_page_controller.rb
ruby
1def manage 2 @introductions = Introduction.all 3 @introduction = Introduction.new 4end
manage.html.erb
erb
1<% @introductions.each do |introduction| %> 2<%= render 'introductions/form', introduction: introduction %> 3<br><br><br> 4<% end %> 5<%= render 'introductions/form', introduction: @introduction %>
_form.html.erb
erb
1<%= form_for(introduction, url: intro_path) do |f| %> 2<div class="field"> 3 <b><%= '追加' if introduction.description.nil? %></b><br> 4 <%= f.text_area :description, class: 'form-control' %> 5</div> 6 7<div class="actions"> 8 <%= f.submit "送信", :class=>"btn btn-success", :style=>"display: inline" %> 9 10<% unless introduction.description.nil? then %> 11 <%= link_to '削除', introduction, method: :delete, class: 'btn btn-danger', :style=>"display: inline" %> 12<% end %> 13</div> 14<% end %>
routes.rb
ruby
1Rails.application.routes.draw do 2 resources :introductions 3 root 'static_pages#index' 4 get 'manage', to: 'static_pages#manage' 5 post 'intro', to: 'introductions#create' 6 delete 'intro', to: 'introductions#destroy' 7 patch 'intro', to: 'introductions#update' 8end
introductions_controller.rb
ruby
1class IntroductionsController < ApplicationController 2 before_action :set_introduction, only: [:edit, :update, :destroy] 3 def new 4 @introduction = Introduction.new 5 end 6 7 def create 8 @introduction = Introduction.new(introduction_params) 9 if @introduction.save 10 @introduction = Introduction.new 11 redirect_to manage_url 12 else 13 render 'new' 14 end 15 end 16 17 def edit 18 end 19 20 def update 21 if @introduction.update(introduction_params) 22 redirect_to manage_url 23 else 24 render :edit 25 end 26 end 27 28 def destroy 29 @introduction.destroy 30 redirect_to manage_url 31 end 32 33 private 34 def set_introduction 35 @introduction = Introduction.find(params[:id]) 36 end 37 38 def introduction_params 39 params.require(:introduction).permit(:description, :id) 40 end 41end
ここでmanage.htmlにて送信ボタンを押すと
ActiveRecord::RecordNotFound in IntroductionsController#update
Couldn't find Introduction with 'id'=
エラーが出ます。
##試したこと
scaffoldコマンド等で得られるedit画面ではURLにidを含めますが、そういったことをしていないのが問題なのかなとも思いました。
###隠しフォームを利用する
隠しフォームを使ってidを送信しようと思い、_form.html.erbに以下の一文を追加しました。
<% f.hidden_field :id, :value => introduction.id %>
しかし、エラー画面のParametersのところにも表示されず、行き詰っております。
少し変わった状況かもしれませんが、IDを取得する方法をご教示いただけますでしょうか。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。