多态模型+控制器的Rails约定

编程入门 行业动态 更新时间:2024-10-10 19:20:43
本文介绍了多态模型+控制器的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 are picturable.
  • 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约定

    本文发布于:2023-08-03 14:28:53,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1287675.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:控制器   模型   多态   Rails

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!