[英]How do I tell ruby on rails to do something such as render a template or redirect if sphinx return 0 results?
有一個問題:
我允許我的用戶通過電子郵件或用戶名搜索他們認識的人。 這按預期工作,但我很難使redirect_to或渲染正常工作。
如果發生以下情況,我如何告訴Rails進行渲染模板或重定向之類的操作:
我的搜索表單實例是否應該在index動作中:
類SearchesController <ApplicationController
def index
@users = User.search params[:search]
@default_photo = Photo.find(@users.first.profile.photo_id) if @users.first.profile.photo_id
end
end
看我的觀點有多混亂:
<% if params[:search].blank? != true %>
<h1> Find more people </h1>
<p> Type in the email address, username or full name of who ever you're trying to find
<br />
<br />
<br />
<% else %>
<h1> Find People </h1>
<p> Type in the email address, username or full name of who ever you're trying to find
<br />
<br />
<br />
<% end %>
<%= form_tag searches_path, :method => 'get' do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
<br />
<br />
<br />
<% if params[:search].blank? != true %>
<div id="paintings">
<% @users.each do |u| %>
<h2> We found: </h2>
<div class="painting">
<div class="gallerycontainer">
<% if @default_photo %>
<a class="thumbnail" href="#thumb"><%= link_to image_tag(u.profile.photo(u.profile.photo_id).image, :width => '100'), u.username %>
<% else %>
<a class="thumbnail" href="#thumb"><%= link_to image_tag("/assets/default_avatar.jpg", :width =>"100"), u.username %> <br />
<% end %>
</div>
<div class="name"><%= link_to u.username, u.username %></div>
<div class="actions">
<%= u.profile.first_name %> <%= u.profile.last_name %>
</div>
</div>
<% end %>
<div class="clear"></div>
</div>
<% end %>
我不得不訴諸所有這些,並且我認為它開始引起混亂。
如果我可以更直接的方式完成上述步驟,則可以繼續並輕松完成此任務。
現在,當用戶不填寫任何內容時,它僅在搜索字段中顯示同一頁面,但是當他們填寫不存在的用戶的信息時,我會得到未定義的方法配置文件。 如果我可以在控制器中處理這個問題,那么事情將會變得容易得多,並且我不需要在視圖中訴諸混亂。
親切的問候
您可以重定向到控制器中的其他操作,如下所示:
def index
if(some_condition)
redirect_to new_model_path
else
redirect_to models_path
end
end
然后您可以有條件地重定向。
在視圖中,可以用相同的方式渲染不同的部分:
<% if(some_condition) %>
<%= render :partial => "my_partial" %>
<% else %>
<%= render :partial => "another_partial" %>
<% end %>
是的,請查看是否可以將部分視圖提取到部分視圖中,或者將它們放在可以重定向到的自己的頁面上,或者僅在視圖中使用條件部分渲染。
使用.empty嗎? 還是空白? 解決了我的問題。 我打開控制台,故意提供了一個不存在的用戶,並看到了空數組[],因此首先在控制器中使用== []起作用了,但我認為必須有一種更好的方式來表示空數組。
做了一些谷歌搜索並最終找到了這篇文章
最終用空了? 在我的控制器中,所有問題都解決了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.