Ruby on rails 如何从控制器A的一个动作重定向到控制器B的动作并返回Rails?

Ruby on rails 如何从控制器A的一个动作重定向到控制器B的动作并返回Rails?,ruby-on-rails,redirect,controller,action,back,Ruby On Rails,Redirect,Controller,Action,Back,我有两个相关模型,员工和公司: class Employee < ActiveRecord::Base attr_accessible :name belongs_to :company attr_accessible :company_id end class Company < ActiveRecord::Base attr_accessible :name, :industry, :owner has_many :employees end *和re

我有两个相关模型,
员工
公司

class Employee < ActiveRecord::Base
  attr_accessible :name

  belongs_to :company
  attr_accessible :company_id
end

class Company < ActiveRecord::Base
  attr_accessible :name, :industry, :owner

  has_many :employees
end
*
和return
语句是必需的,否则会出现“重定向到被多次调用”错误*

然而,这不是理想的行为——原因有二:

  • 即使公司不存在,也会创建员工
  • 未通知用户有关员工创建的信息

因此,我的想法是,我正在以正确的方式重定向到公司控制器和创建操作,并且我应该以某种方式重定向回员工控制器中我所在的位置(就在
@employee.save
之前)。但是怎么做呢?另外,这是最好的也是“最适合rails”的方法吗?

我看到的一个选项是在会话中保存员工数据(
会话[:temp\u employee]=params[:employee]
),然后重定向到创建公司。在公司控制器中,保存公司后,您可以检查员工是否在会话中,然后将客户端重定向回以创建员工控制器的操作

这还需要您:

  • 启用通过路径创建操作的访问权限(例如:
    get'create',to:'employees#create'
  • 在“employees create action take for attributes from session”中,如果存在变量,则返回参数散列

我看到的一个选项是在会话中保存员工数据(
会话[:temp\u employee]=params[:employee]
),然后重定向到创建公司。在公司控制器中,保存公司后,您可以检查员工是否在会话中,然后将客户端重定向回以创建员工控制器的操作

这还需要您:

  • 启用通过路径创建操作的访问权限(例如:
    get'create',to:'employees#create'
  • 在“employees create action take for attributes from session”中,如果存在变量,则返回参数散列
签出路由签出路由
def create
  @employee = Employee.new(params[:employee])

  @company = Customer.find_or_create_by_name(params[:company][:name])
  @company.employees << @employee
  @company.save

  @employee.save
end
# one way to tell if the company has all its attributes filled
if @company.industry.blank?
  redirect_to edit_company_path(@company), notice: "Please edit the company details" and return
end