Rails 4:如何将循环逻辑放在控制器内

时间:2016-09-19 04:44:52

标签: ruby-on-rails ruby loops ruby-on-rails-4 haml

我的haml文档中有四个循环用于测试目的,唯一的区别是元素的顺序。

我能以某种方式将逻辑放在我的控制器中并在我的haml文档中列出循环的整个'insidyness'吗?
目前我已经重复了4次,你知道,这感觉很糟糕。 :)

例如:

- @loop.where(featured: true).order("RANDOM()").limit(4).each do |item|
    %li
        %h1 This is an example
- @loop.order(:cached_votes_up => :desc).limit(4).each do |item|
    %li
        %h1 This is an example
- @loop.order(:impressions_count => :desc).limit(4).each do |item|
    %li
        %h1 This is an example
- @loop.order("created_at DESC").limit(4).each do |item|
    %li
        %h1 This is an example

控制器:

def index
    @loop = Item.all
end

我想将我的Haml代码缩减为类似的内容并将其余部分移到Controller中:

- @loop.each do |item|
    %li
        %h1 This is an example

提前感谢您的回答!

3 个答案:

答案 0 :(得分:2)

<{1>}模型类中的

Item

在您的观点中:

scope :featured_with_random_order_desc, ->(limit_value) { where(featured: true).order("RANDOM()").limit(limit_value) }

scope :by_cached_votes_order_desc, ->(limit_value) { order(:cached_votes_up => :desc).limit(limit_value) }

scope :by_impression_count_order_desc, ->(limit_value) { order(:impressions_count => :desc).limit(limit_value) }

scope :by_created_at_desc, ->(limit_value) { order("created_at DESC").limit(limit_value) }

您可以更进一步,为控制器中的每个循环创建变量:

- @loop.featured_with_random_order_desc(4).each do |item|
    %li
        %h1 This is an example
- @loop.by_cached_votes_order_desc(4).each do |item|
    %li
        %h1 This is an example
- @loop.by_impression_count_order_desclimit(4).each do |item|
    %li
        %h1 This is an example
- @loop.by_created_at_desc.limit(4).each do |item|
    %li
        %h1 This is an example

并在视图中使用它们:

def index
  @loop_featured = Item.featured_with_random_order_desc(4)
  @loop_cached_votes = Item.by_cached_votes_order_desc(4)
  @loop_impression_counts = Item.by_impression_count_order_desclimit(4)
  @loop_by_created = Item.by_created_at_desc(4)
end

答案 1 :(得分:2)

您无法多次渲染视图,但您可以执行此类操作。

def index
  @loops = [
    Item.where(featured: true).order("RANDOM()"),
    Item.order(:cached_votes_up => :desc),
    Item.order(:impressions_count => :desc),
    Item.order("created_at DESC")
  ]
end

然后在模板中

- @loops.each do |loop|
 - loop.limit(4).each do |item|
   %li
     %h1 This is an example

答案 2 :(得分:0)

您可以使用union_scope

中的ActiveRecord
    #item.rb

    include ActiveRecord::UnionScope
    scope :by_random, -> { where(featured: true).order("RANDOM()").limit(4) }
    scope :by_cached_votes, ->{ order(:cached_votes_up => :desc).limit(4) }
    scope :by_impression_count, ->{ order(:impressions_count => :desc).limit(4) }
    scope :by_created_at, ->{ order("created_at DESC").limit(4) }

    scope: all_conditions, -> { union_scope(by_random, by_cached_votes,by_impression_count,by_created_at}

你的控制器

@item = Item.all_conditions

你的观点:

- @loop.all_conditions.each do |item|