2016-06-17 2 views
0

У меня есть функция поиска в рельсах, которая должна отображать страницу для отображения грантов, которые были получены при поиске. Однако, когда вы выполняете поиск, шаблон визуализируется несколько раз, а не один раз, и его визуализируется поверх себя, поэтому он выглядит как загроможденный беспорядок. Я не уверен, где ошибка, но она должна вызывать рендеринг более одного раза. Heres мой метод контроллера:Функция поиска рендеринга Rails многопользовательская

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 раз

ответ

1

Вы случайно столкнулись Rails коллекция рендеринга. Вы можете прочитать об этом здесь: https://robots.thoughtbot.com/rendering-collections-in-rails

Когда вы

<%= render @grants %> 

Rails интерпретирует это как вы желая оказать grants/_grant.html.erb (я думаю - или какой-то аналогичный путь) парциальное один раз для каждого гранта.

Если вместо этого вы хотите сделать это только один раз, попробуйте

<%= render "grants/grant" %> 

(переименование парциального к чему-то вроде «_grants.html.erb» и рендеринга, которые могут также быть хорошей идеей, просто так это Безразлично Похоже, что он предназначен для предоставления одного гранта.)

Смежные вопросы