Search code examples
ruby-on-railsruby-on-rails-3.2associationserbrefinerycms

How to reference attributes in deep associations


Summary

Rails 3.2 with RefineryCMS 2.0. These are my pseudocode models:

Industry
  name
  has_many companies
  has_many works through companies

Company 
  name
  has_many works
  belongs_to industry

Work
  name
  belongs to company

From an instance of Work, I can say work.company.name and get a the name of the associated company. I would expect it to follow that I could also say company.industry.name without a problem. However, I am getting an unhelpful error:

wrong constant name Refinery:Industries

What I would ultimately like to do is follow my associations all the way up ie work.company.industry.name, but the chain is broken between company and industry it seems. What am I doing wrong here? Here's my code in more detail.


Code

Here are my models. Any idea what would prevent me from accessing industry attributes from an associated company given that industries have_many companies (companys lol) and companies belong_to an industry? Any help would be much appreciated.

Industry Model

module Refinery
  module Industries
    class Industry < Refinery::Core::BaseModel
      ...

      attr_accessible :name, :description, :position
      has_many :companys, :class_name => '::Refinery::Companys::Company', :dependent => :nullify
      has_many :works, :through => :companys
    end
  end
end

Company Model

module Refinery
  module Companys
    class Company < Refinery::Core::BaseModel
      ...

      attr_accessible :name, :position, :industry_id
      has_many :works, :class_name => '::Refinery::Works::Work', :dependent => :destroy
      belongs_to :industry, :class_name => '::Refinery:Industries::Industry'
    end
  end
end

Work Model

module Refinery
  module Works
    class Work < Refinery::Core::BaseModel
      ...

      attr_accessible :name, :description, :position, :company_id
      belongs_to :thumbnail, :class_name => '::Refinery::Image'
      belongs_to :Company, :class_name => '::Refinery::companys::company'
    end
  end
end

Then in my erb file I'm doing this:

<% @works.each do |work| %>          
    ...
    <h5>
      <%= work.company.name %>
    </h5>
<% end %>    

That one works.
This one gives me an error though:

 <% @clients.each do |client| %>
   <h5>
       <%= client.industry.name %>
   </h5>
 <% end %>

That error reads:

wrong constant name Refinery:Industries

Solution

  • There is at least a double colon missing in your Company model:

    belongs_to :industry, :class_name => '::Refinery:Industries::Industry'
    

    should be

    belongs_to :industry, :class_name => '::Refinery::Industries::Industry'
    

    I haven't really looked at the rest of the code, but this is a first error.