2012-04-24 64 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