我无法弄清楚要选择哪些参数来进行以下情景的比较。
我想链接到我网站上的特定页面,具体取决于使用哪个范围来获取我主页上显示的数据。这可能吗?
例如我有一个帖子和部门模型,关系就是这样
发布
belongs_to :department
系
belongs_to :post
我通过范围抓取帖子,然后有一个方法从其范围中抓取第一个帖子。
scope :tynewydd_posts, :include => :department, :conditions => {"departments.name" => "Ty Newydd"}, :order => "posts.published_on DESC"
scope :woodside_posts, :include => :department, :conditions => {"departments.name" => "Woodside"}, :order => "posts.published_on DESC"
然后显示每个
的第一篇文章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
在我看来,我会遍历热门帖子
<% @toppost.each do |t| %>
<%= link_to 'Read more' %> <!-- Want to put a helper method here -->
<% end %>
路线
/tynewyddnews #tynewydd_posts
/woodsidenews #woodside_posts
在@toppost实例变量中,我有属性department.name可用,我通过我的.each循环中的t.department.name访问。
我如何说“if @ toppost.department.name ==”xxxx“然后link_to”/ path“例如。只是寻找一些关于结构的提示或者是否可以将其转换为case语句然后会更好
由于
答案 0 :(得分:1)
您可以使用哈希而不是数组,然后只返回密钥,因为您不需要它们的值:
def self.top_posts
top_posts = { "tynewydd" => self.tynewydd_posts.first,
"woodside" => self.woodside_posts.first,
"sandpiper" => self.sandpiper_posts.first,
"outreach" => self.outreach_posts.first
}
top_posts.delete_if {|x| x.value==nil}
return top_posts.keys
end
现在你得到一个像这样的哈希键数组:
["tynewydd","woodside",..]
在你看来:
<% @toppost.each do |t| %>
<%= link_to 'Read more', "#{t}news_path" %>
<% end %>