Problem rendering partials dynamically

1

I have the following code:

<table class="table table-bordered table-striped" border="0">
  <% @time_line.each do |time_line| %>
    <%= render partial: partial_name( get_type(time_line) ), locals: { register: time_line } %>
  <% end %>
</table>

@time_line is a variable that concatenates records from multiple models. To complicate matters more, for each type of object, I need a different view (it's a project requirement, I can not change). So, to make it easier to maintain afterwards, I thought of doing it above. The methods codes I used to try to call the partials dynamically:

def partial_name(class_name)
  partial_names = {
    "Custa" => 'financial',
    "Andamento" => 'course',
    "Movimentacaoweb" => 'web_movement',
    "Publicacao" => 'publication',
    "Audiencia" => 'hearing',
    "Anotacao" => 'anotation'
  }

  partial_names[class_name.to_s]
end

def get_type(obj)
 obj.class.to_s == 'Mensagem' ? obj.model.to_s : obj.class.to_s
end

For some reason, when I run, it gives the following error:

  

'nil' is not an ActiveModel-compatible object that returns a valid partial path.

Does anyone know how to explain what I'm doing wrong?

    
asked by anonymous 21.05.2015 / 20:21

2 answers

0

Dude, I may be freaking out, but are you sure @time_line is an instance variable?

If it really is, it will always be nil in your context because you are calling time_line instead of @time_line !! So to solve the problem just change this line:

<table class="table table-bordered table-striped" border="0">
  <% @time_line.each do |time_line| %>
    <%= render partial: partial_name( get_type(time_line) ), 
                        locals: { register: time_line } %>
  <% end %>
</table>

To:

<table class="table table-bordered table-striped" border="0">
  <% @time_line.each do |time_line| %>
    <%= render partial: partial_name(get_type(@time_line)), 
                        locals: { register: @time_line } %>
  <% end %>
</table>

UPDATE 02

I've been parsing again and seen, one possible problem: "your render statement". How about switching to:

<%= render partial_name(get_type(time_line)), locals: { register: time_line } %>

Thanks!

    
22.05.2015 / 14:25
0

Rails knows how to find the partial of a model automatically.

link

  

If you have an instance of a model to render into a partial, you can   use shorthand syntax:

     

<%= render @customer %>

     

Assuming that the @customer instance variable   contains an instance of the Customer model, this will use   _customer.html.erb to render it and will pass the local variable customer into the partial which will refer to the @customer instance   variable in the parent view.

So your code could be changed to:

<table class="table table-bordered table-striped" border="0">
  <% @time_line.each do |tl| %>
    <%= render tl, locals: { register: tl } %>
  <% end %>
</table>
    
22.05.2015 / 19:29