I am trying to use a polymorphic comment model on the post model , upload model, etc. Ordinarily i would have a @parent resource to scope one to the other in order for Rails to build the relationship. But because this a multi-tenant subdomain styled application, where all resources will also need to be scoped to the curent_account. I am struggling with how to scope @parent resource under the current_accout.
In ApplicationController I have a current_account method, a find_parent and a parent_collection method:
#Application_controller
class ApplicationController < ActionController::Base
before_filter :current_account
def current_account
unless is_root_domain?
@current_account ||= Account.find_by_subdomain(request.subdomains.first)
end
@current_account
end
def find_parent
params.each do |name ,value|
@parent = $1.pluralize.classify.constantize.find(value) if name =~ /(.*?)_id/
return if @parent
end
end
def parent_collection
@parent_collection ||= current_account.send parent.pluralize
end
end
#comments_controller with only @parent resource without reference to current_account
class CommentsController < ApplicationController
before_filter :find_parent
def new
@comment = @parent.comments.build
end
def create
@comment = @parent.comments.build(params[:comment])
.....
.....
end
end
#comments_controller using only current_account resource without reference to @parent
class CommentsController < ApplicationController
before_filter :current_account
def new
@comment = current_account.comments.build
end
def create
@comment = current_account.comments.build(params[:comment])
.....
.....
end
end
Any guide on how to call current_accout in the controllers in a way that @parent is scoped to it and is there a need for the parent_collection method that i put in the applications_controller. Thanks
Let’s make an assumption that your @parent resource is a
Postmodel. Then I would imagine that:a) your
Accountmodelhas_many :postsb) your
Postmodelbelongs_to :accountc) your
Postmodelhas_many :comments, :as => :commentablec) your
Commentmodelbelongs_to :commentable, :polymorphic => trueSo with that in mind you should be able to build scopes like this:
You can also refactor it to the commentable model:
and the use it in the controller like this: