Rails - 关联字段无法按预期为外部表工作。

时间:2016-09-07 17:47:41

标签: ruby-on-rails

我使用rails连接到外部数据库。我有一个具有字段的机会表

如果我使用以下代码,我会得到公司名称。

<% company_id = opportunity.Oppo_PrimaryCompanyId %>
<% @company = CrmTable::Company.where("Comp_CompanyId = ?", company_id) %>
<% @company.each do |company|%>
    <td>
      <%= company.Comp_Name %>

    </td>
<% end %>

然而,根据我对Rails数据库的关联所做的事情,我以为我可以做到

<% company_id = opportunity.Oppo_PrimaryCompanyId %>
<% @company = CrmTable::Company.where("Comp_CompanyId = ?", company_id) %>
<%= @company.Comp_Name %>

当我尝试时,我收到错误

   NoMethodError in Searches#show
Showing C:/Users/cmendla/RubymineProjects/product_development/app/views/shared/_opportunity_list.html.erb where line #56 raised:

undefined method `Comp_Name' for #<Company::ActiveRecord_Relation:0xa734738>
Trace of template inclusion: app/views/searches/show.html.erb

Rails.root: C:/Users/cmendla/RubymineProjects/product_development

Application Trace | Framework Trace | Full Trace
app/views/shared/_opportunity_list.html.erb:56:in `block in _app_views_shared__opportunity_list_html_erb__1021919415_87714420'
app/views/shared/_opportunity_list.html.erb:29:in `each'
app/views/shared/_opportunity_list.html.erb:29:in `_app_views_shared__opportunity_list_html_erb__1021919415_87714420'
app/views/searches/show.html.erb:16:in `_app_views_searches_show_html_erb__1026643635_104558460'
Request

Parameters:

{"id"=>"180"}

如果我执行了@ company.inspect,我会看到以下对应于当前商机的ID

 #<ActiveRecord::Relation [#<Company Comp_CompanyId: 7, Comp_PrimaryPersonId: 7, Comp_PrimaryAddressId: 13, Comp_PrimaryUserId: 35, Comp_Name: "XXX CORPORATION", Comp_Type: "Customer", Comp_Status: "Active", . . .

如果我Company Last<%= @current_company.last %>,我会收到公司最后#<Company:0x9103c50>

CrmTable.rb包含

class Opportunity < CrmTable
  self.table_name = "Opportunity"
  belongs_to :users, class_name: 'CrmUser', foreign_key:  :Oppo_AssignedUserId
  belongs_to :person, class_name:  'Person', foreign_key: :Oppo_PrimaryPersonId
  belongs_to :company, class_name: 'Company', foreign_key: :Oppo_PrimaryCompanyId
end

class Company < CrmTable
  self.table_name = "Company"
  has_many :opportunities
  alias_attribute 'company_name','Comp_Name'
end

同样,我无法理解为什么我必须使用opportunity.company.Comp_Name

来查看公司记录副本。

我不确定大写是否会导致问题。然而,这是外部表设计方式的结果。

2 个答案:

答案 0 :(得分:1)

<% @company = CrmTable::Company.where("Comp_CompanyId = ?", company_id) %>

返回一个集合(CrmTable :: Company数组)。如果要在每个项目上调用Comp_name

@company.map(&:Comp_name)

但显然你想要将变量重命名为公司并相应地前进。

答案 1 :(得分:1)

<% @company.each do |company|%>
    <td>
      <%= company.Comp_Name %>

    </td>
<% end %>

此处@company是公司对象的数组。如果您期待对象,则应在first上使用@company。它将返回一个对象。

<% @company = CrmTable::Company.where("Comp_CompanyId = ?", company_id).first %>

<% @company = CrmTable::Company.find_by_Comp_CompanyId(company_id) %>
 <% if @company %>
   <%= @company.Comp_Name %>
  <% end %>