2016-09-30 9 views
0

私は家主モデルを持っています。テーブルにはlisting_agent_idのフィールドがあります。また、すべての情報が保存されているエージェントモデルもあります。インデックスビューで私は<%= landlord.listing_agent.nameを試していますが、エラーが続いています。私は自分の家主のコントローラにエージェントを定義しましたが、それでもまだ機能していないようです。どんな助けもありがとう。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

*_idという列があるため、ActiveRecordは関連付けを「自動」で作成しません。遠隔的に有用なものは2つだけあります。セットアップするには

あなたがどうなるLandlordAgentとの間の関連性:

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 

ActiveRecordのは、アソシエーションの名前からクラスを推測することはできませんので、class_name: 'Agent'オプションが必要とされています。 inverse_ofは、単一のオブジェクトをメモリ内に保持することによって不一致を避けるのに役立ちます。

関連する問題