本文介绍了多态模型+控制器的Rails约定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Pictures的多态模型.用户,组和页面是picturable.
每个用户,组和页面的嵌套pictures控制器(例如users/5/pictures)
Polymorphic model for Pictures. Users, groups, and pages are picturable.
Nested pictures controller for each of users, groups, and pages (e.g. users/5/pictures)
我有用户,组和页面.每条记录可以有图片.
I have users, groups, and pages. Each record can have pictures.
这是我的体系结构:
这是最标准的设置吗?我会忘记任何Rails约定吗?
Is this the most standard set up? Am I forgetting any Rails convention?
routes.rb示例如下:
resources :users do resources :picturespictures_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约定
发布评论