Rails Polymorphic Associations Plus Routes

I have a model, Report, which is polymorphic. So many yen on my site can have many of them.

And I would like to have a common controller for publishing it. Its very simple model has only text message and association.

in my routes im doing something like

map.resources :users, :has_many => [ :reports ]
map.resources :posts, :has_many => [ :reports ]

but in my report_controller, I would like to get a relationship out with it coming.

as:

before_filter :get_reportable

def get_reportable
   reportable = *reportable_class*.find params[:reportable_id]
end

Is it possible?

how can i get reportable_class and reportable_id?

I can get params [: user_id] when it comes from the user controller, or params [: post_id] when it comes from messages. I could do business with all relationships, but it doesn't seem like a clean solution at all ...

having a polymorphic bond would be the best, is there any way?

+3
2

, , , . , :

before_filter :load_reportable

def load_reportable
  if (params[:user_id])
    @user = User.find(params[:user_id])
    @reportable = @user
  elsif (params[:post_id])
    @post = Post.find(params[:post_id])
    @reportable = @post
  end
rescue ActiveRecord::RecordNotFound
  render(:partial => 'not_found', :status => :not_found)
  return false
end

, - :

before_filter :load_reportable

def load_reportable
  unless (@reportable = @report.reportable)
    # No parent record found
    render(:partial => 'not_found', :status => :not_found)
    return false
  end

  # Verify that the reportable relationship is expressed properly
  # in the path.

  if (params[:user_id])
    unless (@reportable.to_param == params[:user_id])
      render(:partial => 'user_not_found', :status => :not_found)
      return false
    end
  elsif (params[:post_id])
    unless (@reportable.to_param == params[:post_id])
      render(:partial => 'post_not_found', :status => :not_found)
      return false
    end
  end
end

, , , , , " " " ". , :: BaseController, .

, / /, . , . , .., .

, .

+4

:

before_filter :get_reportable

def get_reportable
  params.each do |name, value|
    if name =~ /(.+)_id$/
      @reportable = $1.classify.constantize.find(value)
    end
  end
end

_id, .

0

Source: https://habr.com/ru/post/1728622/


All Articles