我的routes.rb中有一些重复出现的模式,我想通过创建一个为我创建这些路径的方法来使其干掉.
我可以在Devise gem中看到我想要完成的一个示例,您可以使用以下语法:
#routes.rb
devise_for :users
Run Code Online (Sandbox Code Playgroud)
这将产生Devise所需的所有路线.我想创造类似的东西.比方说我有以下路线:
resources :posts do
member do
get 'new_file'
post 'add_file'
end
match 'files/:id' => 'posts#destroy_file', :via => :delete, :as => :destroy_file
end
resources :articles do
member do
get 'new_file'
post 'add_file'
end
match 'files/:id' => 'articles#destroy_file', :via => :delete, :as => :destroy_file
end
Run Code Online (Sandbox Code Playgroud)
这开始变得很乱,所以我想找到一种方法来做这样的事情:
resources_with_files :posts
resources_with_files :articles
Run Code Online (Sandbox Code Playgroud)
所以我的问题是,如何创建resources_with_files方法?
我已经设置了一个模型结构,允许不同的模型通过has_many ...:through ...关联文件模型,该关联也是多态的,因此文件可以属于许多不同的模型,不同的资源可以有很多文件.
然后,File模型属于Attachment模型,它是实际文件,但我使用File模型来跟踪不同的版本.附件模型知道文件是否是图像.
这是基本的模型结构:
class Resource < ActiveRecord::Base
has_many :file_associations, :as => :association
has_many :files, :through => :file_associations
...
end
class FileAssociation < ActiveRecord::Base
belongs_to :r_file
belongs_to :association, :polymorphic => true
...
end
class File < ActiveRecord::Base
has_many :file_associations
belongs_to :attachment
named_scope :images, lambda { { :include => :attachment,
:conditions => "attachments.type = 'AttachmentImage'" } }
...
end
Run Code Online (Sandbox Code Playgroud)
然后,我使用此设置从特定资源中检索具有附件的所有文件,该附件是图像,如下所示:
@resource.files.images
Run Code Online (Sandbox Code Playgroud)
当我检查由此生成的SQL查询时,它包含了使用FileAssociation两次加入Resource的条件:
SELECT ....
FROM `files`
LEFT OUTER JOIN `attachments` ON `attachments`.id = `files`.attachment_id
INNER JOIN `file_associations` ON `files`.id = …Run Code Online (Sandbox Code Playgroud)