Reputation: 1499
I try to make my CRM application works and can't figure out where broken part is. When trying to create new contact, on link '/companies/1/contacts/new' got 'NoMethodError in Contacts#new'.
Screenshot is attached, see code below. Please help to find mistake..
route.rb is:
Rails.application.routes.draw do
resources :companies do
resources :contacts do
member do
post :new
end
end
end
root 'companies#index'
end
Contacts Controller:
class ContactsController < ApplicationController
before_action :set_company
def index
@contacts = Contact.where(company_id: params[:company_id])
end
def new; @contact = @company.contacts.new; end
def create
@contact = @company.contacts.create(contact_params)
@contact.save ? redirect_to @company : render :new
end
private
def set_company; @company = Company.find(params[:company_id]); end
def contact_params
params.require(:contact).permit(:name, :position, :phone, :email)
end
end
View: new.html.erb:
<%= render 'form' %>
<%= link_to 'Back', company_contacts_path %>
Form helper:
<%= form_for(@contact) do |f| %>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Upvotes: 1
Views: 85
Reputation: 24337
You need to specify the company as the first argument to form_for
:
form_for(@company, @contact)
Then form_for
will be able to infer the correct path.
Upvotes: 2