Rails has_many通过默认值ActiveRecord

时间:2016-09-28 10:24:40

标签: ruby-on-rails activerecord has-many-through

目前我正在开发一个应用程序,它涵盖了一些非常基本的文档管理。 在此期间,出现了一个问题。

以下是该方案:

我对用户和文档有一个经典的多对多关系(用户可以下载许多文档,许多用户可以下载文档)。

在此应用程序中,有#34;公共文档"这应该是每个人都可以访问的。

这里明显的(和天真的)解决方案是添加"公共文档"到每个新用户的映射表。但这真的很天真,我不想编写一个将这些元素插入映射表的例程,这也会浪费数据库存储。

问题

Rails中是否有办法将这些公共文档(通过标记标记)添加到ActiveRecord中的用户可下载文档中?

实施例

文档

SELECT product.title as pTitle, category.title AS cTitle

用户

Id   |   Name   |   IsPublic
------------------------------
1    |   Test   |   false
2    |  Public  |   true

可下载文件:

Id   |   Name
--------------------
1    |   sternze

我现在想要做的是:

User_id   |   Doc_id
----------------------
   1      |      1

我的协会如下:

@user = User.find(1)
@user.documents  # -->  now contains documents 1 & 2
# I don't want to add rows to the documents inside the controller, because the data is dynamically loaded inside the views.

我无法找到一种简单的方法来完成我想要的东西,但也许我忽略了一些东西。

1 个答案:

答案 0 :(得分:3)

在公共文档的文档中创建范围

class Document
  scope :public, -> {public?}
end

创建用户方法' all_documents'

class User

  def all_documents
    documents + Document.public
  end

end

然后在迭代中使用all_documents而不是documents

相关问题