Search code examples
ruby-on-railscontrollerroutesnested-resources

Rails: Nested routes for associated model records


My main objective is to pass the profile id and the company id in with the params hash so that Update the join between the 2 models

The models are setup up, where a profile belongs_to a company and a company has may employees(profiles) as shown in the code at the bottom.

I want to use the employee controller to add, remove and show profile associations with a company.

but when I try to do this I'm getting the following error

No route matches {:action=>"show", :controller=>"employees", :company_id=>#<Profile id: 1, user_id: 1, first_name: "Aaron", last_name: "Dufall", created_at: "2012-06-30 07:49:00", updated_at: "2012-07-01 14:03:24", deleted: false, company_id: 1>}

when does it want to show when I have specified delete as the method as showen in the code below

show.html.erb

<% @employees.each do |employee| %>
   <%= link_to full_name(employee), employee %>
   <%= link_to "Remove", company_employee_path(employee), :method => :delete %>
<% end %>

routes.rb

resources :companies do
  resources :employees
  resources :requests do
    put 'accept', :on => :member
  end
end

company.rb

class Company < ActiveRecord::Base
  attr_accessible :name

  has_many :employees, 
           :foreign_key => 'company_id', 
           :class_name => "Profile"

  has_many :requests, as: :requestable

  validates :name,  presence: true, length: { maximum: 50 }, uniqueness: true

end

profile.rb

class Profile < ActiveRecord::Base
  belongs_to :user
  belongs_to :company
  has_many :requests
  has_many :requested, as: :requestable

  attr_accessible :first_name, :last_name


  validates :first_name, presence: true
  validates :last_name, presence: true

end

Solution

  • Use resource instead of resources in routes.rb.