我有一个用户类,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 %>
也许不是最干净的解决方案,但它似乎工作。
为什么你不使用标准导轨关系的任何原因? ('belongs_to','has_many',...) – Romain 2012-04-24 08:54:53
我是。具体来说,我有:用户has_many继续,恢复has_many项目和belongs_to用户,项目belongs_to恢复。 – 2012-04-24 08:59:39
如果您在模型中创建了这些关系,则不需要这些方法。你可以做'@ user.resumes.paginate'和'@ resume.items.paginate'。您正在尝试Rails已经为您做的工作。 – Mischa 2012-04-24 09:23:14