0

Situation

  • I have two models cables and status
  • Cables belongs to status, and status has many cables
  • Anywhere that is returning a single record the following code works

    @cable.status.stat #where stat is one of the columns in status
    
  • However since my index returns All cables, when I try to access them from view by doing the following

    <% @cables.each do |cable| %>
        <td><%= cable.Cable_Hex %></td>
        <td><%= cable.status.stat %></td>
      </tr>
    <% end %>
    

I get an error stating that .stat is not recognized. When I remove .stat and leave it as cable.status then I just see an address.

If I try to access the foreign_id then I can see it without a problem. Clearly then associated methods are not readily available in view.

How do I access associated model methods from a view?

--Edit-- Including both Models as requested

Model for Cables

class Cable < ActiveRecord::Base
    belongs_to :user, :inverse_of => :cables
    belongs_to :status, :inverse_of => :cables
end

Model for Status

class Status < ActiveRecord::Base
    has_many :cables, :inverse_of => :statuses  
end
Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
  • for some reason my code is not showing in the question, just to let you know I am working on it –  Jan 21 '13 at 13:53
  • Maybe there is not Status associated with the Cable object (or one of the `@cables` list). Try to replace `cable.status.stat` with `cable.status.try(:inpsect)`. This should output a description of the status associated, if exists. Then come back to us if you can't figure out where the problem is. – MrYoshiji Jan 21 '13 at 14:28
  • Hello MrYoshiji, I can say with 100% certainty that they are correctly associated. The first reason is in my View => Show @cable.status.stat works properly, and in even in the rails console it works the way its supposed to. I tried .try(:inspect) but since there were no errors it just output the usual with \\ –  Jan 21 '13 at 16:00

2 Answers2

0

May be wrong sql for association.

SQL -

Cable.where("cables.status_id IS NOT NULL")

To get Status record you can use join

 Status.joins( :cables ).where("cables.status_id IS NOT NULL")

This will return all Status records that have an association with Cables.

Then you can loop through it to get stat for each status.

sjain
  • 23,126
  • 28
  • 107
  • 185
  • Hello Saurabh, I will result to this option last because I dont really understand the cause. the association already works part time, but it doesnt in a very specific case –  Jan 21 '13 at 16:13
0

Cause of the problems were faulty test vectors. They were not initialized properly and the error returned for this was that stat method was not found. This made me think that there was something wrong with passing the method across to view however I have learnt that for this particular problem there are two sides to consider. Information that is currently being used to render the page AND proper associations.