我有兩個關聯模型,Employee
和Company
:如何從控制器A的一個動作重定向到控制器B的動作並返回到Rails?
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
我想要實現的是,當在新員工的形式,用戶類型的公司名稱不存在,他/她應該是重定向到新的公司形式,名稱字段已填寫上一個表單的值,填寫它以便創建公司,然後重定向到「員工成功創建」頁面(但當且僅當公司首先被創建)。
我已成功在員工創建的同時創建一個公司,下面的代碼:
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
然而,這並沒有給我填寫公司的其餘選項信息。
試用redirect_to
,我也設法發送用戶到編輯公司的表格。
# 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
*的and return
聲明是必要的,否則我得到一個「的redirect_to的被稱爲多次」錯誤*
然而,這並不是所期望的行爲 - 的原因有兩個:
- 即使公司沒有創建員工。
- 用戶未被通知員工創建。
所以,我的想法是,我重定向到公司控制器和行動創造正確的方式,我應該以某種方式重定向回我在員工控制器是(前右@employee.save
)其中。但是如何?此外,這是最好的和「最軌道」的方式來做到這一點?
檢出路由http://guides.rubyonrails.org/routing.html – fneron 2013-04-08 20:05:35