LoginSignup
0
0

More than 3 years have passed since last update.

railsのredirect_to

Posted at

Railsで、ページ遷移の際に、配列エラーが出て、かなり悩んだ際のメモ

状況

レコードを投稿し、投稿後にレコード一覧画面へ移行する。
レコードの投稿は出来ているが、ページ遷移が出来ない。
(newページから、cretaeアクションを通してindexページに移行する際にエラーが発生)

article_cnotroller.rb
class ArticleController < ApplicationController
    def index
        @article = Article.all
    end

    def new
        @article = Article.new()
    end

    def create 
        @article = Article.new(article_params)
        if @article.save
            render 'index'
        else
            render 'new'
        end
    end

    private 
    def article_params
        params.require(:article).permit(:main_text, :title, :header_photo, :maintext_photo)
    end

end

簡単ではありますが、保存後にindexページに移行するようにと思い、上記のコードを記述しています。

こちらも簡単に、投稿内容のタイトルだけを表示させるコードにしています。

index.html.erb

<% @article.each do |article| %>
    <tr>
        <td><%= article.title %></td>      
    </tr>

<% end %>
<br>

エラー内容はスクショの通りです。

スクリーンショット (43).png

エラーの内容は、eachが使えないと出ています。。

投稿内容のデバックを取っても、ちゃんと?配列が投稿できてるし、配列のエラーでは無いっぽい!けど何が原因か分からない!状態でした。

投稿は出来ているものの、createアクションを通した際に、

<% @article.each do |article| %>

配列が入っていないことは確かで、どこか怪しげ。

render 'index'

犯人はこいつだ!とまで分かると、エラーの内容はすぐわかりました!!

renderでアクションを呼び出すと、ページのデータのみが呼び出されるんです!
エラーページで見えなかったんですが、恐らく、http://localhost:3000/article/indeじゃなくて、http://localhost:3000にindex.html.erbのページが呼び出されている。はず。

なので、こう書き替えました。

class ArticleController < ApplicationController
    def index
        @article = Article.all
    end

    def new
        @article = Article.new()
    end

    def create 
        @article = Article.new(article_params)
        if @article.save
            redirect_to :action => 'index'
        else
            render 'new'
        end
    end

    private 
    def article_params
        params.require(:article).permit(:main_text, :title, :header_photo, :maintext_photo)
    end

end

redirect_toでアクションを呼び出すと、URL付きのページで呼び出されるみたいです。

なかなか手ごたえのあるエラー内容でした。
楽しいーーー!!!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0