繁体   English   中英

无法显示其他模型的信息

[英]Can't show information from another model

我在Rails上做了一个应用程序,并且试图在与其他表的关系中使用type_id列

我的桌子:

险恶的人

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

请有人可以帮我吗?

就像@backpackerhh所说,默认约定是sinister_type_id ,而不是type_id 但是,如果要覆盖它,则需要指定:foreign_key

型号:

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

class SinisterType < ActiveRecord::Base
   has_many :sinisters
end


控制器:

@sinisters = Sinister.find(:all)


查看:

不是@sinisters.each |sinister| do @sinisters.each |sinister| do ,但是@sinisters.each do |sinister|

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM