Rails Controller Def在保存时创建重定向到URL

时间:2013-01-09 14:53:59

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

def create
  @purchase = Purchase.new(params[:purchase])

  if session[:purchase_id] != @purchase.save
    redirect_to(@purchase, :notice => "Thank you. You good lookin person you.")
  end
end

我正在尝试

A - 重定向到URL或其他控制器路径,或

B - 刷新他们订购的表格(new_purchases_path)和flash:注意用户购买成功。当我尝试添加一个Url(这将是一个感谢消息页面)时,我会收到语法错误。此代码将用户重定向到索引列表(它们无法访问)

如果我取出def create,默认情况下会闪烁一个通知并向他们显示已完成的表单。我正在使用simple_form,我不知道如何覆盖这些默认值。有关至少重定向到网址的任何建议吗?

2 个答案:

答案 0 :(得分:3)

示例:

A - 重定向到URL或其他控制器路径

  redirect_to :action => "show", :id => 5
  redirect_to "http://www.rubyonrails.org"
  redirect_to  new_purchases_path
  redirect_to  purchases_url
  redirect_to :back

B - 刷新他们订购的表格(new_purchases_path)

  render :action => "new"

编辑:

这是flash消息的一般示例:

if @foo.save
  redirect_to foos_path, :notice => "Foo saved"
else
  flash[:notice] = "Some errors occured"
  render :action => "new"
end

答案 1 :(得分:1)

这是我今天制作的创建方法的一个例子

def create
 @book = Book.new(params[:book])
 if @book.save
  redirect_to searchbook_path, notice: 'Book was successfully saved'
 else
render :action => 'results'
end

所以在你的情况下你可以试试这个

def create
@purchase = Purchase.new(params[:purchase])
if @purchase.save
 redirect_to purchase_path, :notice 'Thanks for your purchase'
else
render :action => 'new'
end
end

这假设您有购买和新路径...虽然如果您能告诉我们您遇到的错误会有所帮助