2017-01-29 11 views
1

ネストされた属性を持つモデルがあります。私はcollection_selectを働かせることができません。ここでは、私が要約するRailsでネストされた属性を持つcollection_selectを書き込む方法

class Client < ActiveRecord::Base 
    belongs_to :contact 
    belongs_to :person, dependent: :destroy 
    accepts_nested_attributes_for :person, allow_destroy: true 
end 

class Contact < ActiveRecord::Base 
    has_many :clients 
    belongs_to :person, dependent: :destroy 
    accepts_nested_attributes_for :person, allow_destroy: true 
end 

class Person < ActiveRecord::Base 
    has_one :client 
    has_one :contact 
    belongs_to :personal_title 
    # Returns the combined personal title, first and surname 
    def name 
    [ 
     personal_title.nil? ? '' : personal_title.title, 
     first_name || '', 
     last_name || '' 
    ].reject(&:empty?).join(' ') 
    end 
end 

を持っているものだClientcontact_idperson_idを持ち、Contactperson_idを持っており、Personpersonal_title_idを持っています。私のフォーム上に私は持っています

<div class="field"> 
    <%= f.label :contact_id %><br> 
    <%= f.collection_select(:contact_id, Client.all, :id, :name, 
    {include_blank: true}) %> 
</div> 

私はどこに問題があるか知っていますが、ドキュメントから私はそれを修正する方法を解決できません。私が得るエラーはundefined method 'name' for #<Client:0x6c01350>です。そのとおりです。 name()は、ClientではなくPersonで宣言されています。私はそれが私がcontact.person.name、ないcontact.nameを使用していたので、これは動作します

<select name="client[contact_id]"> 
    <% Contact.all.each do |contact| %> 
    <option value="<%= contact.id %>"><%= contact.person.name %></option> 
    <% end %> 
</select> 

、で動作するように取得することができます。

答えて

1

モデルでは、クライアントは名前を返すメソッドではありません。 名前を返すメソッドは、Personクラスにあります。

人物の名前を返すようにClientでメソッドを作成してください。

class Client < ActiveRecord::Base 
    belongs_to :contact 
    belongs_to :person, dependent: :destroy 
    accepts_nested_attributes_for :person, allow_destroy: true 

    def name 
    self.person.name 
    end 

end 
+1

それを修正しました。もちろん、今はとても分かりやすいようです。ありがとう。 – RamJet

関連する問題