0

我有一个控制器#new,用作根路径。

路由.rb

  resources :participants

  root :to => 'participants#new'

耙路线

    participants GET    /participants(.:format)          participants#index
                 POST   /participants(.:format)          participants#create
 new_participant GET    /participants/new(.:format)      participants#new
edit_participant GET    /participants/:id/edit(.:format) participants#edit
     participant GET    /participants/:id(.:format)      participants#show
                 PUT    /participants/:id(.:format)      participants#update
                 DELETE /participants/:id(.:format)      participants#destroy
            root        /                                participants#new

这在访问 xxx.xx/ 时效果很好

但是当我在控制器中渲染 #new 时,我被重定向到 /participants ,我该如何阻止这种情况发生?

  def create

    @participant = Participant.new(params[:participant])

    respond_to do |format|
      if @participant.save
        format.html { redirect_to root_path, notice: "<h2>Tack!</h2> <p>Registrering genomförd, vi har skickat ut ett mail med instruktioner till #{@participant.email}</p>".html_safe }
        format.json { render json: @participant, status: :created, location: @participant }
      else
        format.html { render action: "new" }
        format.json { render json: @participant.errors, status: :unprocessable_entity }
      end
    end
  end

日志:

Started POST "/participants" for 127.0.0.1 at 2013-03-13 13:21:29 +0100
Processing by ParticipantsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"dXmuTX/ugwgNjc21PPdiSHDGlNXEEGZCRHVIWKELOuw=", "participant"=>{"company"=>"asd", "f_name"=>"asd", "l_name"=>"asd", "email"=>"asd@asd.com", "phone_number"=>"asd", "allergy"=>"asd"}, "commit"=>"Anmäl mig!"}
  MOPED: 127.0.0.1:27017 COMMAND      database=damn_development command={:count=>"models", :query=>{"company"=>"asd", "_type"=>{"$in"=>["Participant"]}}} (0.7780ms)
  MOPED: 127.0.0.1:27017 QUERY        database=damn_development collection=models selector={"email"=>"asd@asd.com", "_type"=>{"$in"=>["Participant"]}} flags=[] limit=1 skip=0 batch_size=nil fields={:_id=>1} (0.5569ms)
  Rendered participants/_form.html.erb (4.7ms)
  Rendered participants/new.html.erb within layouts/application (5.5ms)
Completed 200 OK in 25ms (Views: 19.8ms)
4

2 回答 2

1

您被发送到的原因/participants是因为这是创建操作的路线。除非您更改路线和表格,否则您无能为力。在您的路线中,您可以将 create 操作与 '/' 匹配,但只能通过post. 然后在您的表单中,使用“/”作为操作。

于 2013-03-13T12:27:57.190 回答
0

root / participants#new当你这样做时,请看这条线rake routes。因此,您的路线将带您到participants#new.

如中routes.rb,当你使用root :to => 'participants#new'然后redirect_to root_path,它会去到participants#new你使用的任何地方/,它相当于root_url

例如:

当您在本地编写以下网址时:

http://my_host_name/

它实际上会——

http://my_host_name/participants/new

因此,在您的创建操作中,您有这一行:

format.html { redirect_to root_path, notice: "...."}

它正在重定向到 -

http://my_host_name/participants/new
于 2013-03-13T12:45:37.503 回答