2013-04-07 35 views
0

我之前沒有使用過case語句,並且想知道如何執行以下操作。在幫手中使用case語句

我有一些新聞網頁,相關部門各有職位,所以我抓住每一個從這些最新的帖子,和顯示這些內容的網頁

/tynewyddnews 
/woodsidenews 
/outreachnews 
/sandpipernews 

在我的主頁。

郵政型號

def self.top_posts 
#Array with each of the 4 departments - first record 
top_posts = [ 
    self.tynewydd_posts.first, 
    self.woodside_posts.first, 
    self.sandpiper_posts.first, 
    self.outreach_posts.first 
] 
#remove entry if nil 
top_posts.delete_if {|x| x==nil} 
return top_posts 
end 

tynewydd_posts例如是一個範圍

scope :tynewydd_posts, :include => :department, :conditions => {"departments.name" => "Ty Newydd"}, :order => "posts.published_on DESC" 

所以,如果我讀從tynewydd主頁上後,想創建一個鏈接到/ tynewyddnews或我我正在閱讀從woodside的帖子,並希望link_to/woodside我已被告知案件陳述可能有幫助,但我不確定要使用什麼參數,所以我迄今的嘗試是

def public_news 
case Post.top_posts 
    when :tynewydd_posts == 'Ty Newydd' 
    link_to('...Read more', tynewyddnews_path) 
    when :woodside_posts == 'Woodside' 
    link_to('...Read More', woodsidenews_path) 
end 

然後在我看來,我可以打電話給助手

<%= public_news %> 

顯然是一個可憐的嘗試,首先在示例中我看到時的情況下被設置一個變量被設置?如果有人能就如何實現這一點,將是非常讚賞

+0

def public_news path = case when Post.tynewydd_posts then tynewyddnews_path when Post.woodside_posts then woodsidenews_path ... else default_path end end link_to('...Read More', path) end 

when expression將會啓動哪些標籤:tynewydd_posts和:woodside_posts,你如何比較常量與另一個常量? – megas 2013-04-07 20:22:15

+0

即時通訊非常不確定在這裏,我已經更新問題,建議ty_newydd帖子例如是我的後期模型中的範圍。我比較什麼來區分每個帖子? – Richlewis 2013-04-07 20:26:12

回答

0

試試這個變種一些建議:當expression評估爲真

+0

謝謝你,你介意解釋一下這裏發生了什麼,或者指出一個可以幫助我更好地理解病例陳述的資源。當我嘗試這個時,每個鏈接都指向tynewyddnews – Richlewis 2013-04-07 21:23:29