Rails convention for a polymorphic model + controller

自闭症网瘾萝莉.ら 提交于 2019-12-11 07:11:35

问题


I have users, groups, and pages. Each record can have pictures.

Here is my architecture:

  1. Polymorphic model for Pictures. Users, groups, and pages are picturable.
  2. Nested pictures controller for each of users, groups, and pages (e.g. users/5/pictures)

Is this the most standard set up? Am I forgetting any Rails convention?

routes.rb example looks like this:

resources :users do
  resources :pictures

pictures_controller.rb looks like this:

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

回答1:


Yup. That's pretty much what I've been using from my past projects that have required polymorphic image models.

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

end



来源:https://stackoverflow.com/questions/23944676/rails-convention-for-a-polymorphic-model-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!