實現

2012-12-24 41 views
-1

我有員工模型,其中我有很多控制器 像實現

jobs_controller.rb 
contacts_controller.rb 
personals_controller.rb 
dependets_controller.rb 

它們都與員工控制器。 我正在使用MongoDb,因爲我有不同的控制器,我也有不同的模型。 在我的儀表板中,我必須顯示相關的員工詳細信息。其中一個字段來自聯繫人控制器,另一個來自dependents_controller,另一個來自個人控制器。 在這裏,我必須調用所有模型並從每個模型中取一個字段。 我可以通過顯示來自一個相關模型的每個字段來自定義此代碼。 我正在使用設計。不能我存儲每個用戶相關數據的ID和調用通過用戶模型? 我搞砸了..如果是的話那怎麼樣? 在我的員工控制器

def index 
    @employees = Employee.all 
    Employee.includes(:dependants).each do |dependant| 
    p dependant.firstname #example of pulling data for that related entity 
    end 


    end 

而且我怎麼能定位到相關人員的數據?

回答

2

看看這部分的mongoid文檔:http://mongoid.org/en/mongoid/docs/relations.html 它應該給你一個很好的指示你如何在你的模型中實現關係邏輯。

不過,我強烈建議你閱讀這首: http://docs.mongodb.org/manual/core/data-modeling

特別是參考和原子部分

我過去抓出來不能完全把握蒙戈和交易數據庫引擎(如InnoDB的),它使我通過一個項目重新設計我的車型中旬方式之間的差異。

class Employee 
    include Mongoid::Document 
    field :address, type: String 
    field :work, type: String 
    has_many :dependants 
end 

class Dependant 
    include Mongoid::Document 
    field :firstname, type: String 
    field :lastname, type: String 
    belongs_to :employee 
end 

在你的控制,那麼你可以通過員工訪問家屬數據:

根據要求

由我的第一個鏈接描述你可以設置你的模型像這樣的澄清

#this example loops through every employee in the collection 
Employee.includes(:dependants).each do |employee| 
    employee.dependants.each do |dependant| 
    p dependant.firstname #example of pulling data for that related entity 
    end 
end 
+0

可以給我一些與我的控制器相關的編碼示例嗎?如果是這樣,那麼它會男性我快速趕上我的答案 – regmiprem

+0

我試過了..但我沒有得到它。假設我有員工場2場:地址,類型:字符串 領域:工作類型:字符串和兩個領域依賴字段:姓名,類型:字符串 領域:名字,類型:字符串那我怎麼才能實現,在型號並且也在員工控制器中。你可以編輯代碼嗎?由於 – regmiprem

+0

員工的我的索引控制器是這樣的高清指數 @employees = Employee.all Employee.includes(:家屬)。每個辦|依賴|格式|拉力數據爲相關實體 結束 的respond_to做的 p dependant.firstname#示例| format.html#index.html.erb format.json {渲染JSON:@employees} 結束 結束它給錯誤未定義的方法'姓」爲#<員工:0x0000000201a2f0> – regmiprem