问题
I have users, groups, and pages. Each record can have pictures.
Here is my architecture:
- Polymorphic model for
Pictures
. Users, groups, and pages arepicturable
. - 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