3

I have a RoR application and model SomeModel. I have views for this model and I want to know - is there any method to get the view's path? Of course I can use for this model instance

m = SomeModel.new
v = m.class.class_name.pluralize.downcase

It's working, but maybe you know a better way? :)

John Topley
  • 113,588
  • 46
  • 195
  • 237
Alexey Poimtsev
  • 2,845
  • 3
  • 35
  • 63

4 Answers4

1

As @fl00r said, no, there's no general method to do this, as the names of all the views depend on the individual application implementations (not every controller is a resource controller), but you can certainly write some helpers so that you don't have to type m.class.class_name.pluralize.downcase frequently.

module ViewPathHelper
  def resource_view_path(model_obj, action)
     "#{model_object.class.class_name.pluralize.downcase}/#{action}"
  end
end

would be one way to do so.

This seems a somewhat strange request - what do you need the view path for anyway? Are you doing something highly polymorphic? (Because there's this thing called polymorphic_path ...)

Tim Snowhite
  • 3,736
  • 2
  • 23
  • 27
0

Views working with models through controllers layer. Every view is corresponded to some rout/controller action. So path to views related with controller name: app/views/some_controller/{bunch of files}.html.erb

It is not always true, that your views dirname will referred to your model name. So there is not universal method to find out views dirname.

Your solution is suitable but not in all cases

fl00r
  • 82,987
  • 33
  • 217
  • 237
0

If you feel you need the path to a view in your model, chances are you are putting logic into your model that belongs in the controller or helper. You might reconsider how you are partitioning your MVC logic.

aceofspades
  • 7,568
  • 1
  • 35
  • 48
0

to_partial_path does what you are asking.

This is very handy, especially when working with ajax, and/or nested and polymorphic relationships.

Murmel
  • 5,402
  • 47
  • 53
JSpang
  • 186
  • 1
  • 5
  • while this may answer the question, it is better to include the important parts of the solution (you provided via link) in order to get the best out of your answer. link-only-answers (this is what you currently have) have two disadvatages: thay cant be found very good through a search engine and the are invalid as soon as the link gets broken. please think aubout editing you answer :) thanks – cramopy Oct 31 '17 at 12:57