在另一个控制器中重定向到SHOW操作

Cor*_*len 2 ruby ruby-on-rails ruby-on-rails-3

创建与特定帐户关联的人员后,如何重定向回"帐户"页面?

account_id通过URL参数传递给CREATE Person操作,如下所示:

http://localhost:3000/people/new?account_id=1
Run Code Online (Sandbox Code Playgroud)

这是代码:

<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
Run Code Online (Sandbox Code Playgroud)

当我提交上面的表单时,我收到以下错误消息:

Routing Error

No route matches {:action=>"destroy", :controller=>"accounts"}
Run Code Online (Sandbox Code Playgroud)

为什么redirect_to路由到DESTROY操作?我想通过SHOW动作重定向.任何帮助将不胜感激.

num*_*407 7

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
Run Code Online (Sandbox Code Playgroud)

Rails本身就会理解这最后一个选项,确定记录类的路径,并id从中获取#to_param