Search code examples
ruby-on-rails-3has-many-throughpluralize

rails3 view has_many :through attribute


Three models linked via has_many :through

class Bozza < ActiveRecord::Base
  has_many :accessoryvolumes, :dependent => :destroy
  has_many :accessories, through: :accessoryvolumes
  belongs_to :lavorazione

class Accessory < ActiveRecord::Base
  has_many :accessoryvolumes
  has_many :bozzas, through: :accessoryvolumes

class Accessoryvolume < ActiveRecord::Base
  belongs_to :accessory
  belongs_to :bozza

In the view for bozza, the attributes for bozza are accessible

<% @bozza.accessoryvolumes.each do |accessoryvolume| %>
  <%= accessoryvolume.numero %> 
  <%= accessoryvolume.bozza_id %> 
  <%= accessoryvolume.bozza.lavorazione.name %>
  <%= accessoryvolume.accessory_id %> 
  <%= accessoryvolume.accessory.name %>

save for the last item. Any attribute for the relationship to accessory generates and

undefined method `name' for nil:NilClass

evan though accessory_id has a value. How is the related attribute in one instance being picked up and not the other?


Solution

  • The issue is with the plural handling of "accessory". it was a nasty suspicion for many hours....

    This issue arises rather frequently. Pony up and come up with a name that cannot be interpreted mistakenly by rails or someone, somehow, somewhere. Avoid nouns that pluralize irregularly. Moreso when dealing with foreign languages.

    Now

    class Accessorio < ActiveRecord::Base
      has_and_belongs_to_many :lavoraziones
      has_many :accessoryvolumes
      has_many :bozzas, through: :accessoryvolumes
    

    and

    <%= accessoryvolume.accessorio.nome %>
    

    runs as expected