現在Railsでアプリを作成中ですが、自作アクションを作成しバリデーションを効かせるとどうしても画面のレイアウトが崩れ、リロードをかけるとエラーが発生してしまいます。
そこでredirect_toを使いながら戻り先に値を渡せないか調べていたところ
というサイトを見つけました。
新たにサンプルを作成し、updateアクションに対して試してみましたがうまくいきません(m_ m)
エラーの内容もググって見ましたが自分には理解できませんでした。
わかる方がいらっしゃれば教えていただきますようよろしくお願いいたします(m _m)
追記
参考にしていたサイトはこちらですが指摘いただいたとおり、renderを使った処理のためredirect_toでやることは現状の自分の実力ではできるものではないため、アプリ自体の構造を見直してrenderを使った処理にしていきたいと思います。
###エラー内容
When assigning attributes, you must pass a hash as an argument.
###期待する動作
editアクションで入力されたエラー値をupdateアクションでredirect_toを使いeditアクションに渡したい
###動作環境
Ruby:2.3.5
Ruby on Rails: 4.2.10
###参考サイト
Formに入力した値を維持したままリロードする方法
###前準備
rails new sample_1 rails generate scaffold user name:string rake db:create rake db:migrate
config/routes.rb
ruby
1Rails.application.routes.draw do 2 resources :users 3 root to: "users#index" 4end 5
###該当のソースコード
app/controllers/xxx_controller.rb
ruby
1class UsersController < ApplicationController 2 before_action :set_user, only: [:show, :edit, :update, :destroy] 3. 4. 5 # PATCH/PUT /users/1 6 # PATCH/PUT /users/1.json 7 def update 8 @user.update_attributes(user_params) 9 10 if @user.save 11 flash[:notice] = "更新しました!" 12 redirect_to user_path(@user.id) 13 else 14 # ここでエラーが発生しています 15 # When assigning attributes, you must pass a hash as an argument. 16 @user.attributes = params[:user] 17 flash[:notice] = "失敗しました!" 18 redirect_to edit_user_path 19 end 20 end 21. 22. 23 private 24 # Use callbacks to share common setup or constraints between actions. 25 def set_user 26 @user = User.find(params[:id]) 27 end 28 29 # Never trust parameters from the scary internet, only allow the white list through. 30 def user_params 31 params.require(:user).permit(:name) 32 end 33end
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/06/10 04:04
2018/06/11 11:18 編集