Rails - 如何将方法委托给集合

时间:2018-05-02 15:48:10

标签: ruby-on-rails ruby delegates rails-activestorage

我正在使用ActiveStorage通过API上传文件。我的“文件”模型在“Loot”下命名,因此它是“Loot :: Files”。 File模型有一个关联(ActiveStorage)“has_many_attached:files”。

User.rb

has_many :files, class_name: 'Loot::File'

loot / file.rb(Loot :: File)

has_many_attached :files

虽然这有效(我可以调用user.files.files),但是调用文件上的文件真是太丑陋了。

有没有办法保持名称空间“Loot”,但只需要调用user.files来访问ActiveStorage文件?我尝试使用委托,但它似乎无法委托给集合。

更新:我尝试了以下代理

尝试1

User.rb

delegate :files, to: "Loot::File"

有了这个,调用“User.first.files”,我得到以下错误

Traceback (most recent call last):
    2: from (irb):3
    1: from app/models/user.rb:46:in `files'
NoMethodError (undefined method `files' for Loot::File(id: integer, user_id: integer):Class)

尝试2

User.rb

delegate :files, to: :files

错误:

Traceback (most recent call last):
   16: from app/models/user.rb:46:in `files'
   15: from app/models/user.rb:46:in `files'
   14: from app/models/user.rb:46:in `files'
   13: from app/models/user.rb:46:in `files'
   12: from app/models/user.rb:46:in `files'
   11: from app/models/user.rb:46:in `files'
   10: from app/models/user.rb:46:in `files'
    9: from app/models/user.rb:46:in `files'
    8: from app/models/user.rb:46:in `files'
    7: from app/models/user.rb:46:in `files'
    6: from app/models/user.rb:46:in `files'
    5: from app/models/user.rb:46:in `files'
    4: from app/models/user.rb:46:in `files'
    3: from app/models/user.rb:46:in `files'
    2: from app/models/user.rb:46:in `files'
    1: from app/models/user.rb:46:in `files'
SystemStackError (stack level too deep)

尝试3 - 重命名

我尝试将Loot :: Files重命名为Loot:Uploads并使用以下代理

User.rb

delegate :files, to: :uploads

但是在调用User.first.files

时我得到以下内容
NoMethodError (undefined method `files' for #<Loot::Upload::ActiveRecord_Associations_CollectionProxy:0x00007fdb96ca91c0>)

1 个答案:

答案 0 :(得分:-1)

如何使用through并重命名文件关联,例如:

用户:

has_many :loot_files, class_name: 'Loot::File'
has_many :files, through: :loot_files

然后您应该可以使用:

user.loot_files.files
user.files