一对一协会

时间:2017-06-20 08:52:56

标签: ruby-on-rails model controller associations

我有两个模型,我想在一个表格中显示它们。

模型1:

class Name < ActiveRecord::Base
  has_one :employer, :foreign_key => 'application_id'
end

模型2:

class Employer < ActiveRecord::Base
  belongs_to :name, :foreign_key => 'application_id'
end

控制器:

def summary
    @name = Name.all
end

我认为这是:

<% @name.each do |e| %>
 <tr>
   <td ><%= e.application_id %></td>
   <td ><%= e.Name_of_employee%></td>
   <td ><%= e.Employer_name%></td>
 </tr>
<% end %>

这个名字只有一个雇主。 我正在获得“未定义的方法`雇主'# “

TYIA!

1 个答案:

答案 0 :(得分:3)

定义了关联,

has_one :employer, :foreign_key => 'application-id'

注意案例employer,因此必须是小案例,而不是类名

<td ><%= e.employer.name %></td> # name or some other attribute you wish to display

此外,首先包括关联将有助于消除n+1

@name = Name.includes(:employer)