如何重定向到索引而不是显示为获取未定义的方法错误

时间:2013-07-23 13:42:41

标签: ruby-on-rails ruby-on-rails-3

我在render 'form'中使用index.html.erb,当用户提交表单时,他会被带到/ books / 1。相反,我希望他重定向到索引控制器(所以,/ books页面)。

我试过用:

format.html { render action: "index", notice: 'Book Created' }

index.html.erb文件中,我有:

<% @books.each_with_index do |book,index| %>

该页面显示错误:

undefined method each_with_index

以下是我的方法:

def index
  @books = Book.all
  @book = Book.new

  respond_to do |format|
    format.html 
    format.json { render json: @books }
  end
end

def create
  @book = current_user.books.new(params[:book])

  respond_to do |format|
    if @book.save
      format.html { redirect_to @book, notice: 'Book created.' }
      #format.html { render action: "index", notice: 'Book Created' }      
    else
      format.html { render action: "new" }
    end
  end
end

如何将表单重定向到索引页而不是显示页?

2 个答案:

答案 0 :(得分:1)

如果要重定向到索引页面,则应使用redirect_to方法:

def create
  @book = current_user.books.new(params[:book])

  respond_to do |format|
    if @book.save
      format.html { redirect_to action: :index, notice: 'Book created.' }
    else
      format.html { render action: "new" }
    end
  end
end

答案 1 :(得分:0)

更改为controller_path

 def create

  @book = current_user.books.new(params[:book])

  respond_to do |format|
    if @book.save
      format.html { redirect_to tests_path, notice: 'Book created.' }
    else
      format.html { render action: "new" }
    end
  end
end