多态模型+控制器的Rails约定 [英] Rails convention for a polymorphic model + controller
本文介绍了多态模型+控制器的Rails约定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有用户,组和页面.每条记录可以有图片.
I have users, groups, and pages. Each record can have pictures.
这是我的体系结构:
-
Pictures
的多态模型.用户,组和页面是picturable
.
每个用户,组和页面的 - 嵌套
pictures
控制器(例如users/5/pictures
)
- Polymorphic model for
Pictures
. Users, groups, and pages arepicturable
. - Nested
pictures
controller for each of users, groups, and pages (e.g.users/5/pictures
)
这是最标准的设置吗?我会忘记任何Rails约定吗?
Is this the most standard set up? Am I forgetting any Rails convention?
routes.rb
示例如下:
resources :users do
resources :pictures
pictures_controller.rb
看起来像这样:
class PicturesController < ApplicationController
before_filter :load_picturable
def show
@picture = @picturable.pictures.find(:id)
end
# Get permissible for different objects.
def load_picturable
resource, id = request.path.split('/')[1,2] # /photos/1
# Couples this controller to format of URL, not ideal.
@picturable = resource.singularize.classify.constantize.find(id)
end
end
推荐答案
是的.这几乎是我过去需要多态图像模型的项目中一直使用的.
Yup. That's pretty much what I've been using from my past projects that have required polymorphic image models.
在我的最新项目中,我将多态关系标记为可上传,并且使用相同的方法来获取URL数据.
In my latest project, I labelled my polymorphic relation as uploadable and I used the same approach to get URL data.
def load_uploadable
resource, id = request.path.split('/')[1,2]
@uploadable = resource.singularize.classify.constantize.find(id)
end
如果有帮助,这是我的表演功能.
Here's my show function if it helps.
def show
@asset = Asset.find(params[:id])
@assets = @uploadable.assets
respond_to do |format|
format.html
format.json { render json: @asset}
end
结束
这篇关于多态模型+控制器的Rails约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文