Counter on model

Asked

Viewed 187 times

0

I’m looking for a way to add an incremented variable to the id of a div, could someone tell me the most recommended way to do this?

my difficulty in making this increment is due to the Cocoon that is used to call this render

<%= link_to_add_association '+', f, :filtro_questoes,
        'data-association-insertion-node' => "#filter_q",
        'data-association-insertion-method' => "append", id: 'add', class: 'btn btn-primary' %>

have already accessed object attribute <%= f. Count %>, @Count, but nothing worked out

Obs: If you have a better way to do this without calling the model attribute you’re also worth =D

I need to improve my knowledge in Ruby, but I have to finish soon what I’m doing.

model

class Carro < ActiveRecord::Base
    attr_accessor :count

    belongs_to :person

    def self.count(n = 0)
        @count = n+1
    end

    def self.count
        @count
    end

end

view

<div class="control-group nested-fields">

    <div id="carro_div_n <%= f.count %>" class="row form-group" style="border: 1px solid blue; padding: 10px; margin: 10px;">
      <div class="field">
        <h3>Descrição...</h3>
        <%= f.label :carro_id %>
      </div>

      <div class="field col-xs-3">
        <%= f.label :marca_id %>
        <%= f.select :marca_id, 
        options_for_select(
          @marcas.collect { |marca|
          [marca.name.titleize, marca.id] }, 0), {prompt: 'Selecionar marca'}, { id: 'marcas_select', class: 'form-control'} %>
      </div>
      <div id="div_modelo_n" class="field col-xs-3">
        <%= f.label :modelo_id %>
      <%= f.select :modelo_id, options_for_select(@modelos.collect { |modelo|
          [modelo.name.titleize, modelo.id] }, 0), {}, { id: 'modelos_select', class: 'form-control' } %>
      </div>
      <div class="checkbox form-group col-xs-2">
        <%= link_to_remove_association "remove tarefa", f, class: 'btn btn-danger' %>
      </div>
    </div>
</div>
  • What do you want to use this Count for?

2 answers

1

First thing, when you insert the self It is a method he turns into a static method, static in the Java, that is, you should call it so: Carro.count.

If you want an id, simply use the id of the car: Carro.id

But if you really want to count, do it when showing all the cars. For example if you are using a each to show all cars:

<% Carro.all.each_with_index do |carro, count| %>
    <div id="<%= carro.count %>">
        ...
    </div>
<% end %>

1

Have you tried instead of <%= f.count %> use <%= @carro.count %> ?

  • i had already solved this in js, but the page needs to update for the script to work, so I added the code inside the <body> of the page, it worked without the need for F5, can you tell me why this occurs? I’m guessing this happens because of Rails and not js itself

Browser other questions tagged

You are not signed in. Login or sign up in order to post.