创建与特定帐户关联的人员后,如何重定向回帐户页面?
account_id 通过 URL 参数传递给 CREATE Person 操作,如下所示:
http://localhost:3000/people/new?account_id=1
代码如下:
<h2>Account:
<%= Account.find_by_id(params[:account_id]).organizations.
primary.first.name %>
</h2>
<%= form_for @person do |f| %>
<%= f.hidden_field :account_id, :value => params[:account_id] %><br />
<%= f.label :first_name %><br />
<%= f.text_field :first_name %><br />
<%= f.label :last_name %><br />
<%= f.text_field :last_name %><br />
<%= f.label :email1 %><br />
<%= f.text_field :email1 %><br />
<%= f.label :home_phone %><br />
<%= f.text_field :home_phone %><br />
<%= f.submit "Add person" %>
<% end %>
class PeopleController < ApplicationController
def new
@person = Person.new
end
def create
@person = Person.new(params[:person])
if @person.save
flash[:success] = "Person added successfully"
redirect_to account_path(params[:account_id])
else
render 'new'
end
end
end
当我提交上述表格时,我收到以下错误消息:
Routing Error
No route matches {:action=>"destroy", :controller=>"accounts"}
为什么 redirect_to 路由到 DESTROY 操作?我想通过 SHOW 操作重定向。任何帮助将不胜感激。
最佳答案
params[:account_id]
存在于表单中,但是当您将它传递给 create
时,您将它发送到 person
哈希,因此您可以通过 params[:person][:account_id]
params[:account_id]
是 nil
,因此是错误的路线。老实说,我不确定为什么,但是 resource_path(nil)
最终路由到 destroy
而不是 show
。在任何一种情况下,它都是没有 id
参数的中断路由。
# so you *could* change it to:
redirect_to account_path(params[:person][:account_id])
# or simpler:
redirect_to account_path(@person.account_id)
# but what you probably *should* change it to is:
redirect_to @person.account
Rails 天生就会理解最后一个选项,确定记录类的路径,并从 #to_param
id
关于ruby-on-rails - 重定向到另一个 Controller 中的 SHOW 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7102101/