【问题标题】:Getting a value from a table through a foreign key in Rails?通过Rails中的外键从表中获取值?
【发布时间】:2012-12-13 20:05:43
【问题描述】:

您好,我创建了两个模型,

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

在我的灯具表中,我将 team_id 存储在 home_team_id 和 away_team_id 列中。

然后在我的 fixtures/show.html.erb 中显示存储的 id

<p>
  <b>Home team:</b>
  <%= @fixture.home_team_id %>
</p>

如何通过将 team.id 存储在 fixtures 表中来显示 teams 表中的 team.name?

我需要将这一行 更改为其他内容,但不确定是什么?

【问题讨论】:

    标签: ruby-on-rails datatable foreign-keys show relationship


    【解决方案1】:

    http://guides.rubyonrails.org/association_basics.html#belongs_to-association-reference

    使用belongs_to,您可以使用:@fixture.team 访问它,因为您定义了一对多关系,它不应该同时拥有home_team_idaway_team_id,并且会访问适当的关系。

    【讨论】:

    • 我试过@fixture.team.team_id(fixture.home_team_id).name 给了我一个错误我怎样才能用fixtures 表中home_team 列中的值调用团队?
    • 哦,您还需要在belongs_to 中使用foreign_key 选项。因此,您将需要 2 个 belongs_to 语句,例如 belongs_to :home_team, :class_name =&gt; Team, :foreign_key =&gt; :home_team_id 并以 @fixture.home_team 的身份访问它们
    猜你喜欢
    • 2018-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多