Search code examples
ruby-on-railsrubyruby-on-rails-2

Can't show information from another model


I did an application in rails and I'm trying to use a column type_id in relationship with my other table

My tables:

sinisters

+---+----------+---------+
|id | client   | type_id |
+---+----------+---------+
| 1 | Charles  |       1 |
| 2 | Montalvo |       1 |
| 3 | Gabriel  |       2 |
| 4 | Miguel   |       2 |
+---+----------+---------+

sinister_types

+----+--------+   
| id | name   |
+----+--------+ 
|  1 | DANGER |
|  2 | FIRE   |
+----+--------+ 

My controller:

@sinisters = Sinister.find(:all)

My models:

class Sinister < ActiveRecord::Base
   belongs_to :sinister_type
end

class SinisterType < ActiveRecord::Base
   has_many :sinisters
end

My view:

<% @sinisters.each |sinister| do %>
   <%= sinister.client %>
   <%= sinister.type.name %>
<% end %>

I want to show sinister types names.

I tried this code and got nothing:

<%= sinister.sinister_type.name %>

And also tried and got nothing

<%= sinister.type.try(:name) %>

Please somebody can help me?


Solution

  • Like @backpackerhh says, the default convention is sinister_type_id, not type_id. But if you want to override it, you need to specify :foreign_key.

    Model :

    class Sinister < ActiveRecord::Base
      belongs_to :sinister_type, :foreign_key => :type_id
    end
    
    class SinisterType < ActiveRecord::Base
       has_many :sinisters
    end
    


    Controller :

    @sinisters = Sinister.find(:all)
    


    View :

    Not @sinisters.each |sinister| do, but @sinisters.each do |sinister|

    <% @sinisters.each do |sinister| %>
       <%= sinister.client %> :
       <%= sinister.sinister_type.name %>
    <% end %>