implement has_many through association in rails 4

139 views Asked by At

I am working with has_many :through association in Application. I implement association between models like :-

in employee.rb

class Employee < ActiveRecord::Base
 has_many :inventories, through: :employee_inventories
end

in inventory.rb

class Inventory < ActiveRecord::Base
  has_many :employees, through: :employee_inventories
end

in employee_inventories.rb

class EmployeeInventory < ActiveRecord::Base
  belongs_to :employee
  belongs_to :inventory
end

I create a method in InventoryController.rb like:

    def inventory_status
      p 'paramsssssssssssssssssssssssssssss'
      p params
      p employee_inventories_params
      @employee_inventories = @inventory.employee_inventories.build(employee_inventories_params)
      if @employee_inventories.save
      p 'sssssssssssssssssssssssssss'
      redirect_to inventories_path
      else
      p 'aaaaaaaaaaaaaaaaa'
      render :action => :show
   end

     def employee_inventories_params
        params.require(:employee_inventory).permit(:employee_id, :status)
      end

and in view of my application I render this method by this

<%= link_to 'Request for inventory', inventory_status_inventory_path(@inventory),
:class => 'btn btn-success' %>

when I run this this gives me error

ActionController::ParameterMissing (param is missing or the value is empty: employee_inventory)

I want to store employee_id and status in employee_inventory table. please guide me. How to implement? Thankz in advance.

2

There are 2 answers

1
Dinshaw Raje On BEST ANSWER

Please try this code

 def inventory_status
      @employee_inventories = EmployeeInventory.new(employee_inventories_params)
      if @employee_inventories.save
       redirect_to inventories_path
      else
       render :action => :show
      end
   end

and in your view

 <%= link_to 'Request for inventory', inventory_status_inventory_path(@inventory, employee_inventory => {:employee_id => 1, :status => 'test'}),
:class => 'btn btn-success' %>

hope this will help you.

0
Rokibul Hasan On

Probably, there is no data matched with key employee_inventory in def employee_inventories_params thus you are getting this error.

You can inspect params for track what it sending to your controller. In you form params you should get something like following

:employee_inventory => {:employee_id => 1, :status => true}