通过 rails 中的关联实现 has_many 4

implement has_many through association in rails 4

我正在与 has_many 合作:通过应用程序中的关联。我实现了模型之间的关联,例如:-

employee.rb

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

inventory.rb

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

employee_inventories.rb

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

我在 InventoryController.rb 中创建了一个方法,例如:

    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

鉴于我的应用程序,我通过此方法呈现此方法

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

当我 运行 这给了我错误

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

我想在 employee_inventory table 中存储 employee_id 和状态。请指导我。如何实施?提前谢谢。

可能 def employee_inventories_params 中没有与键 employee_inventory 匹配的数据,因此您收到此错误。

您可以 inspect params 跟踪它向您的控制器发送的内容。在你的表单参数中,你应该得到如下内容

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

请尝试此代码

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

在您看来

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

希望对您有所帮助。