您好我已经创建了两个模型,
class Fixture < ActiveRecord::Base
attr_accessible :away_score, :away_team_id, :home_score, :home_team_id, :result, :week
belongs_to :team, :class_name => Team
end
class Team < ActiveRecord::Base
attr_accessible :form, :name
has_many :fixtures, :class_name => Fixture, :foreign_key => :home_team_id
has_many :fixtures, :class_name => Fixture, :foreign_key => :away_team_id
end
在我的fixtures表中,我将一个team_id存储在home_team_id和away_team_id列中。
然后在我的fixtures / show.html.erb中显示存储的id
<p>
<b>Home team:</b>
<%= @fixture.home_team_id %>
</p>
如何通过获取存储在fixture表中的team.id来显示teams表中的team.name?
我需要更改此行&lt;%= @ fixture.home_team_id%&gt;对别的东西但不确定是什么?
答案 0 :(得分:1)
http://guides.rubyonrails.org/association_basics.html#belongs_to-association-reference
使用belongs_to
,您可以使用:@fixture.team
访问它,因为您定义了一对多关系,它应该永远不会同时拥有home_team_id
和away_team_id
,并且会访问相应的一个