您好我试图使用此模型将一些记录添加到我的数据库
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
但我不知道如何启动新表单来创建新记录 我想尝试像
这样的东西def new
employee = ## gotta get the id here in the form
@colleagueship = employee.colleagueships.build(:colleague_id => params[:colleague_id])
@colleagueship.save
end
你怎么看?我如何使用post http方法实现这一目标?我是否必须使用请求保存employee变量并在那里添加employee_id?
答案 0 :(得分:0)
在控制器中
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_tag帮助程序,因为您可以更轻松地使用您想要的任何字段自定义表单,特别是如果您要避免使用allocate_nested_attributes。如果您没有嵌套路线,也可以在employee_id中加入hidden_field_tag。
= form_tag new_employee_colleague_path do
= text_field_tag 'colleageship[name]', placeholder: 'something...'
这些方面的东西应该有效。确保检查params散列以查看值的格式是否正确。