代码之家  ›  专栏  ›  技术社区  ›  Arcath

“合并”多个模型。创建“最近的活动”框

  •  11
  • Arcath  · 技术社区  · 16 年前

    如何合并模型,以便我可以按顺序显示最后10篇文章、提要条目和私人消息?

    文章存储在“post”模型中,并按“created\u at”排序。

    提要条目存储在“Planet”中,并在“Published_at”上订购。

    私人消息存储在“message”中,需要使用以下内容进行筛选:

    :conditions => "receiver_id = #{current_user.id}"
    

    在“创建地点”上订购

    3 回复  |  直到 10 年前
        1
  •  11
  •   Anna B    16 年前

    你必须:

    1. 每个模型的查询元素
    2. 以通用格式合并它们
    3. 分类和限制

    下面是一些代码:

    class Activity < Struct.new(:title, :text, :date); end
    
    limit = 10
    activities = []
    activities += Post.all(:order => 'created_at DESC', :limit => limit).map do |post|
      Activity.new(post.title, post.summary, post.created_at)
    end
    
    activities += Planet.all(:order => 'published_at DESC', :limit => limit).map do |planet|
      Activity.new(planet.title, planet.message, planet.published_at)
    end
    
    activities += Message.all(:conditions => ['receiver_id = ?', current_user.id], :order => 'created_at DESC', :limit => limit).map do |message|
      Activity.new(message.title, message.text, message.created_at)
    end
    
    # descending sort by 'date' field
    sorted_activities = activities.sort_by(&:date).reverse
    
    # 10 most recent elements across all models
    @activities = sorted_activities[0..(limit-1)]
    

    当然,根据您的模型,您必须更改将哪个方法用作“标题”或“文本”。

    但是如果您碰巧需要许多这样的习惯用法,那么应该像我们在中所做的那样使用单表继承。 zena (Rails CMS)。

        2
  •  11
  •   Simone Carletti    16 年前

    我将使用代理类。类可以存储ActiveRecord对象引用和排序字段。

    class ActivityProxy
      attr_accessor :object, :date
      def initialize(object, date)
        self.object = object
        self.date = date
      end
    end
    

    然后加载对象。

    activity = []
    activity += Post.all(:limit => 10, :order => "created_at DESC").map { |post| ActivityProxy.new(post, post.created_at) }
    # and so on with the other objects
    

    最后对对象进行排序

    activity.sort_by(&:field)
    # => here you have the sorted objects
    # and you can iterate them with
    activity.each do |proxy|
      proxy.object.id
      # ...
    end
    
        3
  •  1
  •   Sabrina Leggett    10 年前

    创建提要的另一种方法是创建一个将两者结合在一起的视图,然后让视图拥有自己的模型。

    推荐文章