[英]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.