Metaprogramming with ruby on rails in a partial

0

I'm working on a Ruby on Rails project and I'm working on a module (Financial) it's linked to several models, and depending on the screen the user is able to do it bring a screen with all the financial movements of that object. However I wanted to do only a partial, in the partial I would pass a variable (taken via metaprogramming) to a given field (also get via meta programming)

To try to generate the link I'm doing this:

  <%%= link_to new_financial_path(<%= singular_table_name %>_id: @<%= singular_table_name %>.id), class: 'btn btn-primary pull-right', remote: true do %>
    <span class="fa fa-plus"></span>
    <%= I18n.t('financials.new.new') %>
  <%% end %>

But the system is returning

NoMethodError - undefined method 'singular_table_name' for #<#<Class:0x007ff098434898>:0x007ff0b5c02eb8>

Did you mean? singleton_method:   app / views / financials / _financials.html.erb: 2: in '_app_views_financials__financials_html_erb

asked by anonymous 10.06.2017 / 22:40

1 answer

1

One suggestion is to do so:

1) Create a concern for which templates you may have extract will need to use. Remembering that concerns should be in the models / concern folder so Rails will automatically read the concerns. The code would look something like this:

module Financiable
  extend ActiveSupport::Concern

  class_methods do

    def transactions
      puts "Found: 30 itens"
    end
  end

end

2) Use in your templates the concern created:

class Customer < ActiveRecord::Base
  include Financiable

end

2) Create a partial that receives a "model" variable. It would look like this:

<%%= link_to new_financial_path(model.class.name, model.id), class: 'btn btn-primary pull-right', remote: true do %>
    <span class="fa fa-plus"></span>
    <%= I18n.t('financials.new.new') %>
<%% end %>

3) When you use partial, use this:

<%= render partial: "financial_trancations", locals: { model: cliente } %>

Considering that you have a variable named model client.

4) In the control that loads the data from the partial should have a method that would look like this:

def index
    clazz = params[:model_name].constantize.find(params[:model_id])
    @transactions = obj.transactions if class.respond_to?(:transactions)
end

If everything is in the right place this should work.

Abs!

    
12.06.2017 / 03:20