-1

目前我的主页显示来自不同模型的数据,这些模型是文章、论坛。

我编写的代码显示了来自不同模型的数据,但不是根据创建它们的日期和时间。我的意思是文章中的数据是根据日期和时间显示的,与民意调查相同,但不是作为一个整体,即如果一篇文章是在民意调查之前创建的,那么它不会在民意调查之前显示。

这是因为我在 poll 之后编写了文章代码,并且在控制器中我使用不同的变量从不同的模型中检索数据,并且在视图中我正在循环这些变量,如下所示。

这个主页的控制器代码是

def index
  @col     = Education.select(:college_id).where(user_id: @current_user.id).all
  @users   = Education.select(:user_id).where(college_id: @col.collect(&:college_id)).all 

  @poll    = Poll.where(created_by: @users.collect(&:user_id)).all
  @article = Article.where(user_id: @users.collect(&:user_id)).all

end

在索引视图页面中,我编写了以下代码

        - unless @poll.empty?
            -  @poll.reverse.each do | poll|
                #statusbox
                    .imgbox
                        - if User.find(poll.created_by).basic_info
                            - if User.find(poll.created_by).basic_info.profilephoto?
                                = image_tag User.find(poll.created_by).basic_info.profilephoto.url(:thumb)
                            - else
                                %span no img
                        - else
                            %span no img
                    #welcomeheader

                        %span.bl=User.find(poll.created_by).first_name
                        posted a poll
                        %span.bl= time_ago_in_words(poll.created_at)  
                        ago

                        %p=link_to poll.name,poll


                %br

        - unless @article.empty?
            -  @article.reverse.each do | article|
                #statusbox
                    .imgbox
                        - if User.find(article.user_id).basic_info
                            - if User.find(article.user_id).basic_info.profilephoto?
                                = image_tag User.find(article.user_id).basic_info.profilephoto.url(:thumb)
                            - else
                                %span no img
                        - else
                            %span no img
                    #welcomeheader

                        %span.bl=User.find(article.user_id).first_name
                        posted an article
                        %span.bl= time_ago_in_words(article.created_at)  
                        ago

                        %p=link_to article.name,article


                %br

有没有一种方法可以存储来自这些不同模型的数据并将其存储在单个变量中并通过它进行循环,或者任何其他方式可以在单个视图中显示来自其他模型的更新日期和时间

4

1 回答 1

1

正如我在您的代码中看到的那样,对于所有 4 个模型,您都显示相同类型的数据,为此您可以创建一个无表模型

class PostWrapper
    store_in nil
    belongs_to :user, :inverse_of => nil

    field :created_at, type: Time
    field :content, type: String
    filed :post_type, type: String
    and all other fields
end

您可以为这些模型的对象分配值并在视图中使用它

或者

如果您的所有 4 个模型都有一些共同的属性和行为,那么您可以尝试 STI(单表继承)链接(http://code.alexreisner.com/articles/single-table-inheritance-in-rails.html ) 然后使用该表的对象并相应地在视图中使用它。

于 2012-05-15T09:37:41.207 回答