Search code examples
ruby-on-railsrubyviewnested-attributes

Rails - Nested attributes views are not shown


I am using join table and nested attributes for collecting list of investor interests in a separate table for investor profiles. For some reasons my view is empty and not showing the investor_interest text field to update. Can you please find it why? My code below.

investor_profile.rb

class InvestorProfile < ApplicationRecord
  belongs_to :user

  has_many :investor_profile_interests
  has_many :investor_interests, through: :investor_profile_interests

  accepts_nested_attributes_for :investor_profile_interests

end

investor_interest.rb

class InvestorInterest < ApplicationRecord
  has_many :investor_profile_interests
  has_many :investor_profiles, through: :investor_profile_interests
end

investor_profile_interest.rb

class InvestorProfileInterest < ApplicationRecord
  belongs_to :investor_profile
  belongs_to :investor_interest

end

investor profile controller

def new
  @investor_profile = InvestorProfile.new
end

views

<%= form_with model: @investor_profile, class: 'form new-profile-form' do |f| %>
   <div class="field">
      <%= f.fields_for :investor_profile_interests do |test| %>
        <%= test.text_field :investor_interest %>
      <% end %>
   </div>
  <div class="field">
      <%= f.submit 'Submit', class: 'button is-primary is-normal' %>
   </div>
<% end %>

Solution

  • In new method, build investor_profile_interests -

    def new
      @investor_profile = InvestorProfile.new
      @investor_profile.investor_profile_interests.build
    end