使用随机视图渲染集合

时间:2014-04-17 03:49:17

标签: ruby-on-rails ruby

例如,我有一些帖子:

@posts = Post.first(20)

@posts.each do |post|
  .box
    - kind = ['big', 'small', 'xs'].sample
    = render "posts/#{kind}", post: post
  #There I need to render view with 
  #different partial ['big', 'small', 'xs', 'long', ...]
  #If 'big' - I should take one post
  #If 'small' - I should take two posts
  #If 'xs' - I should take three posts

我的输出应如下所示:

.box
  div.big
    one post info
.box
  div.small
    first post info
    second post info
.box
  div.xs
    first post info
    second post info
    third post info

也许我应该使用哈希来构建这个集合?

 {"big" => "post", "small" => ["post", "post"], 
  "xs" => ["post", "post", "post"], "small" => ["post", "post"], 
  "xs" => ["post", "post", "post"],"big" => "post"}

或手动创建多个收藏模板?例如:

  .box
    = render "posts/big", post: posts[0]
  .box
    - posts[1..2].each do |post|
      = render "posts/small", post: 
  .box
    - posts[3..5].each do |post|
      = render "posts/xs", post: post

2 个答案:

答案 0 :(得分:0)

选择随机值,打印它,从posts数组中删除打印值,直到它变为空白。

@posts = Post.first(20)

while (!@posts.blank?) do
 puts ".box"
 kind=[{'type'=>'big','size'=>1}, {'type'=>'small','size'=>2}, {'type'=>'xs','size'=>3}].sample
 puts kind['type']

 printed = @posts.sample(kind['size']).collect { |post| 
   render "posts/#{kind['type']}", post: post
   post
 }

 @posts -= printed   
end

答案 1 :(得分:0)

第一行应该移动到帮助者或演示者中:

- { :big => 1, :small => 2, :xs => 3 }.to_a.each do |partial_name, number|
  = render "posts/#{partial_name}", collection: posts.shift(number)