无法显示其他模型的信息

时间:2014-03-18 17:30:55

标签: ruby-on-rails ruby ruby-on-rails-2

我在rails中做了一个应用程序,我正在尝试使用与其他表关系的列type_id

我的桌子:

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   |
+----+--------+ 

我的控制器:

@sinisters = Sinister.find(:all)

我的模特:

class Sinister < ActiveRecord::Base
   belongs_to :sinister_type
end

class SinisterType < ActiveRecord::Base
   has_many :sinisters
end

我的观点:

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

我想展示险恶的类型名称。

我尝试了这段代码而一无所获:

<%= sinister.sinister_type.name %>

还尝试了什么都没有

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

请有人帮助我吗?

1 个答案:

答案 0 :(得分:1)

我认为sinister表上的列应该是sinister_type_id(而不是type_id),或者您需要在模型上指定外键。

相关问题