之前我没有使用过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 :(得分: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
评估为真时 expression
将启动