2012-04-24 65 views
0

我有一個用戶類,has_many恢復,其中每個都有很多項目。在我的用戶/展示頁面上,我呈現了多份正在工作的簡歷。在我users_controller我有以下幾點:如何訪問模型中的ID

def show 
... 
@resumes = @user.resumes.paginate(page: params[:page]) 
@resume = @user.resumes.build if user_signed_in? 
@resume_items = @user.res.paginate(page: params[:page]) 
@edu_items = @resume.edu.paginate(page: params[:page]) 
... 
end 

我在用戶模型中定義的函數RES:

def res 
    Resume.where("student_id = ?", id) 
end 

這相當奏效。不過,我試圖做的功能EDU同樣的事情在我的簡歷模板:

def edu 
    Education.where("resume_id = ?", id) 
end 

,但它不工作,@edu_items沒有被設置成任何東西。現在我知道這與該方法具體有關,因爲如果我將id更改爲特定簡歷的id,那麼該簡歷的項目將正確呈現,除了每個簡歷之外。我知道這是一個簡單的解決方法,在這一點上我只是一直盯着它,並且無法弄清楚。任何建議都會很棒。

編輯:@ makaroni4:而不是@educations = @ user.educations,我寧願保持從每個簡歷項目分開。是否有可能定義一種方法,如教育將使@educations = @ resume.educations?

編輯2:我設法得到了我正在努力工作,感謝您的建議。我解決它通過去除完全的EDU方法,並傳遞局部變量部分:

<%= render :partial => 'shared/edu', :as => :educations, :locals => {:resume_educations => resume_item.educations} %> 

共享/ edu的

<% if resume_educations.any? %> 
    <ol class="educations"> 
    <%= render partial: 'shared/edu_item', collection: resume_educations %> 
    </ol> 
    <%= will_paginate @educations %> 
<% end %> 

也許不是最乾淨的解決方案,但它似乎工作。

+1

爲什麼你不使用標準導軌關係的任何原因? ('belongs_to','has_many',...) – Romain 2012-04-24 08:54:53

+0

我是。具體來說,我有:用戶has_many繼續,恢復has_many項目和belongs_to用戶,項目belongs_to恢復。 – 2012-04-24 08:59:39

+1

如果您在模型中創建了這些關係,則不需要這些方法。你可以做'@ user.resumes.paginate'和'@ resume.items.paginate'。您正在嘗試Rails已經爲您做的工作。 – Mischa 2012-04-24 09:23:14

回答

2

我認爲你的模型結構應該是這樣的:

class User < ActiveRecord::Base 
    has_many :resumes 

    def educations 
    Education.joins(:resume => :user).where(:users => { :id => id }) 
    end 
end 

class Resume < ActiveRecord::Base 
    belongs_to :user 
    has_many :educations 
end 

class Education < ActiveRecord::Base 
    belongs_to :resume 
end 

所以在你的控制器,你可以訪問他們喜歡的:

@resumes = @user.resumes 
@educations = @user.educations # all users educations, from all resumes 

or 

@educations = @resume.educations # educations for particular resume 

同時,我建議你閱讀這篇文章http://petdance.com/2012/04/the-worlds-two-worst-variable-names/關於變量命名,變量如resume_items和方法resedu應該說你不是以正確的方式做smtg。

+0

這不會讓我輸入長評論,所以請參閱上面的編輯 – 2012-04-24 10:31:03

+0

當然,educations = resume.educations將與我的示例一起工作,請檢查我的編輯答案 – makaroni4 2012-04-24 11:05:30

1

它不起作用,因爲您的edu方法的結果將始終爲空。如果您使用build一個對象被創建,但不保存到數據庫中尚未

@resume = @user.resumes.build if user_signed_in? 

在你的代碼正在建設一個恢復對象。這意味着您的@resume.idnil。因此,您的edu方法的結果將爲空。

你可以使用以下方法來創建數據庫中的記錄:

@resume = @user.resumes.create if user_signed_in? 

但是你edu方法仍然會返回一個空的集合,因爲它是一個新的記錄,它不會與任何項相關聯然而。

請詳細說明您正在嘗試做什麼,因爲使用此代碼@resume.edu將因上述原因而始終爲空。

另外:考慮使用內置的Rails功能,而不是製作自己的方法。

+0

我認爲我設法弄清楚我正在嘗試做什麼..請參閱上面的編輯 – 2012-04-24 10:50:40