Note that there are some explanatory texts on larger screens.

plurals
  1. POGet object of relation n:m in Ruby on Rails
    primarykey
    data
    text
    <p>I have two models:</p> <ol> <li>Perfiles</li> <li>Modulos</li> </ol> <p>And the relationship between them is: Many to Many, there is a table to map relation: modulos_perfiles</p> <p>I need get all "modulos" that belongs to "perfil".. I have this:</p> <pre><code>&lt;% @perfiles.each do |perfil| %&gt; &lt;% @m = perfil.modulo.last %&gt; &lt;%= @m.ruta %&gt;&lt;br/&gt; &lt;% end %&gt; </code></pre> <p>but I get this error: </p> <blockquote> <p><strong>undefined method "ruta" for nil:NilClass</strong></p> </blockquote> <p>Where "ruta" is a column of "modulo" table.</p> <p>I made this:</p> <pre><code>&lt;% @perfiles.each do |perfil| %&gt; &lt;% @m = perfil.modulo.last %&gt; &lt;%= debug @m %&gt;&lt;br/&gt; &lt;% end %&gt; </code></pre> <p>And I can see all attributes of @m object so:</p> <p>ruby/object:Modulo</p> <p>attributes:</p> <ul> <li>id: 7 </li> <li>descripcion: Busquedas</li> <li>ruta: /busquedas</li> <li>created_at: 2012-11-25 02:23:51.984916000 Z</li> <li>updated_at: 2012-11-25 02:23:51.984916000 Z </li> </ul> <p>But I don't understand why I cannot get this attributes with:</p> <pre><code>&lt;%= @m.ruta %&gt; </code></pre> <p>Any idea?, thanks!</p> <p><strong>UPDATE</strong></p> <p>My model classes are:</p> <pre><code>class Perfil &lt; ActiveRecord::Base has_many :usuario has_and_belongs_to_many :modulo end class Modulo &lt; ActiveRecord::Base has_and_belongs_to_many :perfiles end class ModulosPerfiles &lt; ActiveRecord::Base end </code></pre> <p>**</p> <h2>ANSWER</h2> <p>**</p> <p>I don't have enough reputation to publish answer.</p> <p>I've resolved:</p> <p>I made this:</p> <pre><code>&lt;% @perfiles.each do |perfil| %&gt; &lt;% perfil.modulo.each do |modulo| %&gt; &lt;%= modulo.ruta %&gt;&lt;br/&gt; &lt;% end %&gt; &lt;% end %&gt; </code></pre> <p>And so I can get any attribute of object "modulo".</p> <p>Thanks.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload