Rails convention for a polymorphic model + control

2019-08-08 21:24发布

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条回答
SAY GOODBYE
2楼-- · 2019-08-08 22:08

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

查看更多
登录 后发表回答