Trung Tran
Trung Tran

Reputation: 13721

form_for not working rails 4.0

I have a simple form_for in rails that will not create a new record after I click "add". I have a model called Opportunity which has a nested resource called Contact. The form for Contact is the one I am having an issue with. I compared my form to similar nested resources that work, but could not find the issue. Here is my code:

Contacts controller:

  def new
    @contact = Contact.new
  end


  def create

  @opportunity = Opportunity.find(params[:opportunity_id])
  @contact = @opportunity.contacts.new(contact_params)
    if @contact.save
      redirect_to @opportunity, notice: 'Contact has been added'
    else
      redirect_to @opportunity, alert: 'Unable to add Contact'
    end
  end

def contact_params
  params.require(:contact).permit(:first_name)
end

here is the specific form that I am having issues with:

views/contacts/new.html.erb:

    <div id="new_contact_form">

    <%= form_for ([@opportunity, @opportunity.contacts.new]) do |f| %>
        <div class="field">
            <%= f.label "Contact Info:" %> <br />
            <%= f.text_area :first_name %> 
        </div>

        <div class="actions">
            <%= f.submit 'Add' %> 
        </div>
    <% end %>

    </div>

Please help...Thanks!!!

Upvotes: 1

Views: 242

Answers (1)

Mandeep
Mandeep

Reputation: 9173

Change your new action to this:

def new
  @opportunity = Opportunity.find(params[:opportunity_id])
  @contact = @opportunity.contacts.build
end

and your form will be:

<%= form_for ([@opportunity, @contact]) do |f| %>
  // form fields
<% end %>

Upvotes: 1

Related Questions