Ruby on rails Rails多对多模型,添加记录

Ruby on rails Rails多对多模型,添加记录,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,你好,我正在尝试用这个模型向我的数据库添加一些记录 class Colleagueship < ActiveRecord::Base belongs_to :employee belongs_to :colleague, :class_name => 'Employee' end class Employee < ActiveRecord::Base has_many :colleagueships has_many :colleagues, :t

你好,我正在尝试用这个模型向我的数据库添加一些记录

class Colleagueship < ActiveRecord::Base
  belongs_to :employee
  belongs_to :colleague, :class_name => 'Employee'
end

class Employee < ActiveRecord::Base      
  has_many :colleagueships
  has_many :colleagues, :through => :colleagueships
  # ...
end
你觉得怎么样?如何使用post http方法实现这一点?我是否必须将employee变量与请求一起保存,并在那里添加employee\u id?

在控制器中

def new
end

def create
  # inspect submitted params here
  puts params

  if colleagueship.save
    # etc etc
  else
    # error
  end
end

private

def employee
  @employee = Employee.find_by(params[:employee_id])
end

def colleagueship
  @colleagueship = employee.colleageships.build
end

helper_method :employee, :colleagueship
应该嵌套路由,以提供用于查找员工的密钥

resources :employees do
  # this will generate /employees/:employee_id/colleagues/:id
  resources :colleagueships
end
在您看来,您可能会使用form_标记帮助器,因为它更容易使用您想要的任何字段自定义表单,特别是如果您要避免接受您应该接受的嵌套属性。如果没有嵌套路由,还可以包含一个带有员工id的隐藏字段标记

= form_tag new_employee_colleague_path do
  = text_field_tag 'colleageship[name]', placeholder: 'something...'
沿着这条思路应该会奏效。确保检查params散列以查看值的格式是否正确

= form_tag new_employee_colleague_path do
  = text_field_tag 'colleageship[name]', placeholder: 'something...'