2011-02-08 107 views
0

我有一個相當複雜的(在我)語句寫在Rails中。在我的Person.rb這是用戶的個人資料的show.html.erb下。每個post在數據庫中有一個status列,值爲draftpublished簡化這個條件語句

<% if @posts.blank? %> 
    No post. 
<% else %> 
    <% if @person == current_user %> 
    <% @posts.each do |post| %> 
     Post title... (where all published and draft posts are shown) 
    <% end %> 
    <% else %> 
    <% @posts.each do |post| %> 
     <% if post.status == "published" %> 
     Post title (where only published posts are shown, draft posts are hide from other users) 
     <% end %> 
    <% end %> 
    <% end %> 
<% end %> 

問題出在這裏。假設User A有1條已發佈帖子和1條發表帖子,工作正常;但是如果User B有兩篇草稿文章,則右側的任何文章都不會顯示給其他用戶,但是我希望它像第一個2行代碼一樣顯示No post

我試過named_scope在我的Post.rb指導here,但是當我申請.published時,它只是返回了一個未定義的錯誤。

請教我如何做到這一點。非常感謝你。

+0

這是rails 3嗎?我想在rails 3中使用範圍:published => where(:published => true) – corroded 2011-02-08 04:41:07

+0

它是Rails 2.3.8。對不起,以前沒有說過。 – Victor 2011-02-08 05:19:48

回答

2

我會做到以下幾點:

創建的職位上地位的範圍。

 
class Post 
    named_scope :by_status, lambda { |status| {:conditions => {:status => status} } } 
end 

還可以將一些邏輯到控制器中:

 
class PostsController 
    def index 
    @person = Person.find(params[:person_id]) 
    if current_user == @person 
     @posts = @person.posts 
    else 
     @posts = @person.posts.by_status('published') 
    end 
    end 
end 

寫下您的看法:

 
<% if @posts.empty? %> 
    No posts code 
<% else %> 
    <% @posts.each do |post| %> 
    Post title... 
    <% end %> 
<% end %> 

這個解決方案應該幹你的代碼,並把更多的邏輯到模型。

0

爲您解決問題最快的辦法,我只是排除草稿帖子在這樣的第一行:

if (@person == current_user) ? @posts.blank? : @posts.select({ |x| x.status == 'published' }).blank? 

但是,這並不真正簡化你的整體做什麼。這是一個在視圖中很常見的問題(有條件地根據兩個不同的條件做一件事),希望有人更聰明可以分享更好的解決方案。同時,我爲你提供這個。

0
<% @posts.to_a.each do |post| 
    if @person == current_user || post.status == 'published' %> 
     ... 
    <% end 
    end %> 

.to_a將使[]nil的,所以它可能只是減少這個...

+0

謝謝。它有效,但有一個小問題。 `<%@ posts.to_a.each do | post | %> <%if @person == current_user || post.status =='published'%> 文章標題... <% else %> No post code。 <% end %> <% end %>` 如果我有2篇稿子,0篇發表的帖子,它顯示2個「無郵政編碼」。我怎樣才能將它限制爲1? – Victor 2011-02-08 06:39:58