前提・実現したいこと
railsを学習中の初学者です。
railsでの写真の投稿機能を作製中、空の投稿を行った際にエラーが発生してしまいます。
ParameterMissingの示す通り、strongparameterで指定したmicropostが空だと言われていると思うのですが、どのようにコードを記述すれば問題がないのか、解決の方法がわかりません。
micropost_paramsに何も入っていないため@micropost.saveが失敗し、if文のelseの分岐に入らないのはなぜなのだろう?と疑問に思っています。
お力をお貸しいただけると幸いです。
発生している問題・エラーメッセージ
Started POST "/microposts" for 103.5.142.123 at 2018-10-21 08:45:03 +0000 Cannot render console from 103.5.142.123! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255 Processing by MicropostsController#create as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"PPaLrLIV51b+cnsyD5lpWrO+TbisckvNPcVURZWQiu7g+TUR2/wPjTHEJyM+vk5t975hvrQqj+PElz8PaF+dcg==", "commit"=>"Create Micropost"} User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 3], ["LIMIT", 1]] Completed 400 Bad Request in 3ms (ActiveRecord: 0.2ms) ActionController::ParameterMissing (param is missing or the value is empty: micropost): app/controllers/microposts_controller.rb:26:in `micropost_params' app/controllers/microposts_controller.rb:7:in `create'
該当のソースコード
controller
1class MicropostsController < ApplicationController 2 before_action :authenticate_user! 3 before_action :collect_user,only: :destroy 4 5 6 def create 7 @micropost = current_user.microposts.build(micropost_params) 8 if @micropost.save 9 flash[:success] = "Micropost created!" 10 redirect_to root_path 11 else 12 @feed_items = [] 13 render "static_pages/home" 14 end 15 end 16 17 def destroy 18 @micropost.destroy 19 flash[:success] = "Micropost deleted" 20 redirect_to root_path 21 end 22 23 private 24 25 def micropost_params 26 params.require(:micropost).permit(:picture) 27 end 28 29 def collect_user 30 @micropost = current_user.microposts.find_by(id: params[:id]) 31 redirect_to root_path if @micropost.nil? 32 end 33 34end 35
model
1class Micropost < ApplicationRecord 2 belongs_to :user 3 default_scope -> {order(created_at: :desc)} 4 mount_uploader :picture, PictureUploader 5 validates :user_id, presence: true 6 validates :picture, presence: true 7 validate :picture_size 8 9 def picture_size 10 if picture.size > 5.megabytes 11 errors.add(:picture, "should be less than 5MB") 12 end 13 end 14end 15
form
1<%= form_for(@micropost) do |f|%> 2 <%= render 'shared/error_messages', object: f.object %> 3 4<%= f.label :picture%> 5<%= f.file_field :picture,accept: "image/png,image/jpeg"%> 6 7<%= f.submit class: "btn btn-primary" %> 8 9<% end %>

バッドをするには、ログインかつ
こちらの条件を満たす必要があります。