通过rails 4中的关联实现has_many

时间:2015-06-15 09:15:45

标签: ruby-on-rails-4 activerecord has-many-through

我正在使用has_many:通过Application中的关联。我在以下模型之间实现关联: -

InvariantCulture

中的

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

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

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

并且鉴于我的应用程序,我通过此

呈现此方法
    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

当我运行此操作时,这给了我错误

  

ActionController :: ParameterMissing(param丢失或值为   空:employee_inventory)

我想将employee_id和status存储在employee_inventory表中。请指导我。如何实施?提前谢谢。

2 个答案:

答案 0 :(得分:1)

请尝试此代码

 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' %>

希望这会对你有所帮助。

答案 1 :(得分:0)

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

您可以inspect params跟踪发送给控制器的内容。在你形成params你应该得到像下面这样的东西

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