【问题标题】:How can I combine the results of different variables into one variable?如何将不同变量的结果组合成一个变量?
【发布时间】:2012-05-16 06:30:33
【问题描述】:

我的控制器索引操作中有以下四个变量,它们从不同的模型中检索数据,如下所示:

@forum = Forum.where(:user_id => @users.collect(&:user_id)).all
@poll=Poll.where(:created_by => @users.collect(&:user_id)).all
@article = Article.where(:user_id => @users.collect(&:user_id)).all
@jobpost = Jobplacement.where(:user_id => @users.collect(&:user_id)).all

我想将所有这些变量的数据加入一个变量@post。我该怎么做?

【问题讨论】:

  • 为什么要将不同的对象存储在单个变量中?
  • sounder..我想根据创建日期和时间将所有这些变量数据显示到单个页面上。所以我想我会将它存储在一个变量中,然后执行“@post .reverse.each do " 按日期时间顺序显示帖子

标签: ruby-on-rails ruby ruby-on-rails-3 controller


【解决方案1】:

单个集合中有不同类型的对象是不好的。 但正如你所要求的那样尝试

@post = [@forum,@forum,@article,@jobpost].flatten

更新: 当我还是 Ruby 的新手时,我写了这个答案。当我看到这个答案时,我无法控制自己的笑容。 flatten 的目的是从嵌套数组中生成单个数组。答案与问题无关。但我对投票感到惊讶:)

【讨论】:

  • 转到您的 Rails 控制台并尝试 [[1,2],[3,4]].flatten 然后看看会发生什么
  • 这很漂亮,即使它在技术上是“不,不”。
【解决方案2】:

将它们放在哈希中:

@post = Hash.new
@post['forum']   = Forum.where(:user_id => @users.collect(&:user_id)).all
@post['poll']    = Poll.where(:created_by => @users.collect(&:user_id)).all
@post['article'] = Article.where(:user_id => @users.collect(&:user_id)).all
@post['job_placement'] = Jobplacement.where(:user_id => @users.collect(&:user_id)).all

它们没有连接,但它们在一个变量中。您可以随时访问它们,并随心所欲地使用它们。

【讨论】:

  • @post['forum'],@post['poll'],@post['article'],@post['job_placement'] 这些是什么意思。
  • @post['forum'] 表示哈希 @post 的密钥 forum。将哈希视为关联数组(例如在 PHP 中)。我建议您学习一些 Ruby 基础知识,并不时查看文档。 :)
【解决方案3】:

类似这样的:

conditions = { :user_id => @users }  # assuming primary_key is set correctly
                                     # in the User model
@post = Forum.where( conditions ).all   +
        Poll.where( conditions ).all    +
        Article.where( conditions ).all +
        Jobplacement.where( conditions ).all

或者如果你想变得花哨:

models = [ Forum, Poll, Article, Jobplacement ]

@post  = models.reduce [] do |records, model|
  records.push *model.where( :user_id => @users ).all
end

注意:.all 在这两种情况下都可能是不必要的,因为它通常在必要时由 Rails 自动调用,但我不确定。

【讨论】:

    【解决方案4】:

    我认为您需要类似视图模型的概念。创建一个不继承自ActiveRecord::Base 的简单模型类,并将所有对象作为属性添加到新类中并对其进行初始化。

    class Post 
       attr_accessor :forum, :poll, :article, :jobpost
       def initialize(forum,poll,article,jobpost)
          @forum = forum
          @poll = poll
          @article = article
          @jobpost = jobpost
       end
    end
    

    在控制器动作中添加以下内容;

    @post = Post.new(@forum,@poll,@article,@jobpost)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-08
      • 2018-03-03
      • 2022-08-13
      相关资源
      最近更新 更多