2016-09-30 27 views
0

我有一個房東模型,在表中有一個listing_agent_id字段。還有一個代理模型,其中存儲了所有的信息。在索引視圖中,我試圖給我們<%= landlord.listing_agent.name,但不斷收到錯誤。我在我的landlords_controller中定義了代理,但它似乎仍然沒有工作。任何幫助,將不勝感激。NoMethodError - 未定義的方法 - 從Rails 4中的ID拉出名稱

樓主指數:

<tbody> 
    <% @landlords.each do |landlord| %> 
    <tr> 
     <td><%= landlord.listing_agent.name %></td> 
    </tr> 
    <% end %> 
</tbody> 

鬥地主控制器:

def index 
    @landlords = Landlord.all 
end 

def new 
    @landlord = Landlord.new 
    @agents = Agent.employees.order(first_name: :asc) 
end 

業主型號:

class Landlord < ActiveRecord::Base 
    has_many :landlord_addresses 
end 

錯誤:

enter image description here

回答

2

ActiveRecord不會因爲您有一個*_id列而「自動」創建關聯。只有兩種可能性是遠程有用的。

要設置關聯LandlordAgent之間你會做:因爲ActiveRecord的不能從關聯的名稱推斷類需要

class Landlord < ActiveRecord::Base 
    belongs_to :listing_agent, class_name: 'Agent' 
          inverse_of: :landlord 
    # use inverse_of: :landlords if the relation is one to many. 
end 

class Agent < ActiveRecord::Base 
    has_one :landlord, inverse_of: :listing_agent 
    # or 
    has_many :landlords, inverse_of: :listing_agent 
end 

class_name: 'Agent'選項。 inverse_of通過在內存中保留單個對象來幫助避免不一致。

相關問題