1

I how two controllers, Project and SubProject and a table of Reports which has a column which is left empty if is populated from Project and adds the SubProject_id if is populated from SubProject.

Project controller show action

@keywords = @project.keywords

SubProject controller show action

@reports = @project.keywords

In the project#show I render the @keywords and in the _keyword.html.erb partial I have

 <tr>
  <td><%=keyword.id%></td> 
  <td><%=keyword.name%></td>
  <td>
  <%=keyword.reports.where(subproject_id: nil).find_each do |keyword_r|%>
    [<%=keyword_r.possition%>]
  <%end%>
  </td>
</tr>

In my subproject#show I render @reports, and in the _report.html.erb partial I have

 <%report.find_each do |keyword_r|%>
  <tr><td> <%=keyword_r.name%></td>
    <td>
      <%keyword_r.reports.where(subproject_id: !nil).each do |kr|%>
        [<%=kr.possition%>]
      <%end%>
    </td>
  </tr>
<%end%>

The problem is that, if I do <%=render @reports%> it's going to render @keywords. But when I do <%= render partial: "report", locals: {report: @reports}%>, is going to render the correct partial. Why can't I use <%= render @reports%>? Or what I am doing wrong and why in the reports partial I need two loops?

4

1 回答 1

2
<%= render @reports %>

Rails uses the class of the objects to determine which partial to use, not the name of the collection variable. The collection @reports contains Keyword objects, so the _keyword.html.erb partial is used, unless you specifiy otherwise.

See 3.4.5 in Rails rendering guide, you can even have objects of different classes, each object will be rendered with the partial matching its class.

于 2013-11-06T10:55:21.957 回答