开发者

Specifying name of rails partial to render using a variable

Is it possible in Rails 3.0 to render a partial where the name of the partial is stored in a variable?

I am attempting something similar to:

<%= escape_javascript(raw render :partial => @partial_name, :locals => { :value => @value} )%>

Updated with more details

In my application I have a set of models using multi-table inheritance, for example lets say I have a base model 'cupcake' and variants such as 'AwesomeCupcake' and 'AlrightCupcake'.

Each of these models have their own custom partial for displaying information and follow the naming scheme: '_awesome_cupcake' and '_alright_cupcake'.

On a page I have links to each type of cupcake in which I want the controller to accept a parameter and dynamically derive which partial to render. The following works as wanted if (in the new.js.erb file) I replace '@partial_name' with something such as 'awesome_cupcake'.

Here is a little more information into how my components are laid out:

application.js

$('#set_cupcake').click(function () {
   $.getScript('/cupcakes/new.js?cupcake_type=awesome');
});

cupcakes_controller.rb

def new
   cupcake_type = "#{params[:cupcake_type].capitalize}Cupcake"

   if Object.const_defined? cupcake_type
     @cupcake = cupcake_type.constantize.new
     @partial_name = "#{params[:cupcake_type]}_cupcake"
   end
end开发者_如何学Python

views/cupcakes/new.js.erb

$('#cupcakes')
  .append("<%= escape_javascript(raw render :partial => @partial_name, :locals => { :cupcake => @cupcake } ) %>")


Of course. Make sure @partial_variable is a string of the name (such as "header" and it will work fine.


So I finally figured out what the issue was. In my controller I was setting the @partial_name within the scope of a condition that was checking if a specific model existed.

I did not realize that using Object.const_defined? doesn't really work for rails in development mode as the models aren't initially all loaded. An alternate approach I found is to search through a list of database table connections using ActiveRecord::Base.connection.tables.

However I think a better solution is to store some file that 'registers' acceptable values for this parameter.


If that's not working, can you show us exactly what @partial_name contains? What error are you getting?

Make sure that the leading underscore is left out, as well as the file extension.

For example: to render '_myPartial.html.erb', @partial_name should be "myPartial".

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜