我在导轨中具有搜索功能,该搜索功能应渲染一个页面以显示搜索所挑选的赠款。但是,当您搜索时,模板被多次渲染而不是一次渲染,并且它在本身上呈现,因此看起来像是混乱的混乱。我不确定错误在哪里,但是它必须调用渲染多次。这是我的控制器方法:
def index
if params[:search]
@grants = Grant.search(params[:search]).order("created_at DESC")
else
@grants = Grant.all.order('created_at DESC')
end
end
以及我渲染模板的观点的一部分
<% if @grants.present? %>
<%= render @grants %>
<% else %>
<p>There are no grants containing the term(s) <%= params[:search] %>.</p>
<% end %>
<%= yield %>
和模板;
<html>
<body>
<style>div {
margin-left:17%;
padding:1px 16px;
height:1000px;}
</style>
<div>
<center>
<hr style="height:5 px; visibility:hidden;" />
<br>
<font size=6 >
<strong>
<A HREF="/" STYLE="text-decoration: none; color: black">US Federal Grants</a>
<br>
<br>
<hr style="height:5 px; visibility:hidden;" />
</strong>
</font>
</center>
<% if @grants != [] && @grants != nil%>
<table border="1" style="width:100%">
<tr>
<td><strong><font size=5>Title</font></strong></td>
<td><strong><font size=5>Award Ceiling</font></strong></td>
<td><strong><font size=5>Description</font></strong></td>
<td><strong><font size=5>Additional Information</font></strong></td>
<td><strong><font size=5>Closing Date</font></strong></td>
</tr>
<% for item in @grants %>
<tr>
<td><%= item.title %></td>
<% if item.ceiling != '$0' && item.ceiling != nil && item.ceiling != '' && item.ceiling != '$1' && item.ceiling != '$2'%>
<td><%= item.ceiling %></td>
<% else %>
<td> See link for more information </td>
<% end %>
<% if item.description == "" %>
<td>See link for more information</td>
<%elsif item.description == nil%>
<td>See link for more information</td>
<% elsif item.description.sub('Description:', '').length > 720 %>
<td>
<%= truncate(item.description.sub('Description:', ''), length: 720) %>
<%= link_to 'Read more', '', class: "read-more-#{item.id}" %>
<script>
$('.read-more-<%= item.id %>').on('click', function(e) {
e.preventDefault()
$(this).parent().html('<%= escape_javascript item.description.sub('Description:', '') %>')
})
</script>
</td>
<%else%>
<td> <%=item.description.sub('Description:', '')%></td>
<%end%>
<td><center> <a href= <%= item.link %>>LINK</a><center></td>
<%unless item.date == nil%>
<td><% newdate = Date.parse item.date %>
<%= newdate.strftime("%D") %>
</td>
<%end%>
</tr>
<% end %>
<% else %>
<center>
<p> There are no Grants available to Entrepreneurs in this category at this time. However this list updates daily based on Grants.gov data, so feel free to check back later. </p>
</center>
<% end %>
</table>
</div>
</body>
</html>
我不确定它在哪里发生,但它似乎正在渲染大约25次
您意外地遇到了Rails Collection渲染。您可以在此处阅读更多有关它的信息:https://robots.thoughtbot.com/rendering-collections-in-rails
当您做
时<%= render @grants %>
Rails在您想要渲染grants/_grant.html.erb
(我认为 - 或类似路径)的情况下对此进行解释。
如果您只想渲染一次,请尝试
<%= render "grants/grant" %>
(将部分重命名为" _grants.html.erb"和渲染,这可能也是一个好主意,因此看起来它并不是要提供单个赠款。)