开发者

Class name to view path

I have a RoR application 开发者_C百科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? :)


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 ...)


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


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.


to_partial_path does what you are asking.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜