2013-04-08 66 views
1

我有兩個關聯模型,EmployeeCompany如何從控制器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)其中。但是如何?此外,這是最好的和「最軌道」的方式來做到這一點?

+0

檢出路由http://guides.rubyonrails.org/routing.html – fneron 2013-04-08 20:05:35

回答

1

我看到的一個選擇是在會話中保存員工數據(session[:temp_employee] = params[:employee]),然後重定向到創建公司。在公司控制器中,公司控制器保存後,您可以檢查員工是否出席會議,然後重定向客戶端以創建員工控制器的操作。

這還需要你:

  • 允許訪問通過路徑創建操作(如:get 'create', to: 'employees#create'
  • 在員工創造行動採取從會話變量屬性,如果它存在,否則回退到params散列。
相關問題