我有一个控制器#new,我用它作为根路径。
的routes.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时,我被重定向到/参与者,我怎么能阻止这种情况发生呢?
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
LOG:
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)
答案 0 :(得分:1)
您被发送到/participants
的原因是因为这是创建操作的路径。除非您更改路线和表格,否则您无法采取任何措施。在您的路线中,您可以将创建操作与'/'匹配,但仅限于post
。然后在表单中,使用“/”作为操作。
答案 1 :(得分: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