简体   繁体   English

使用HABTM模型将外键自动从视图传递到控制器

[英]Passing foreign key automatically from view to controller using HABTM models

I have two models, Companies and Employees, with a many-to-many association between them. 我有两个模型,公司模型和雇员模型,它们之间有多对多的关联。

class Company < ActiveRecord::Base
    has_and_belongs_to_many :employees
end

class Employee < ActiveRecord::Base
    has_and_belongs_to_many :companies
end

I have a join table :companies_employees 我有一个联接表:companies_employees

class CreateCompaniesEmployeesJoin < ActiveRecord::Migration
    def change
       create_table :companies_employees, :id => false do |t|
          t.integer "company_id"
          t.integer "employee_id"
       end
       add_index :companies_employees, ["company_id", "employee_id"]
    end
end

I have a Show view for Company, which includes a form_for adding a new Employee, who I want to associate with that Company via the HABTM association: 我有一个“公司”的“显示”视图,其中包括一个form_for添加新员工,我想通过HABTM关联将其与该公司相关联:

<%= form_for :employee, :url => employees_path do |f| %>
    <p>
        <%= f.label :name %>
        <%= f.text_field :name, class: 'form-control' %>
    </p>
    <br>
    <p>
        <%= f.hidden_field :company_id, :value => @company.id  %>
    </p>
    <p>
        <%= f.submit "Save Employee", class: "btn btn-default" %>
    </p>

<% end %> 

I have a controller for Employee, through which I want to create a new Employee that will be automatically associated with the Company from the Company Show view: 我有一个用于Employee的控制器,通过它我想创建一个新的Employee,它将从Company Show视图中自动与Company关联:

def create
    @company = Company.find(params[:company_id]) 
    @employee = Employee.new(employee_params)
    @company.employees << @employee

    if @employee.save
        flash[:success] = "Company Employee Added!"
        redirect_to @employee
    else
        render 'new'
    end
end

When I use the form to try to create a new employee, I get an error in EmployeeController -- "Couldn't find Company without an ID" 当我使用表单尝试创建新员工时,在EmployeeController中收到错误消息-“找不到没有ID的公司”

Seems my view is failing to pass the :company_id on to the create action in the EmployeeController. 似乎我的视图无法将:company_id传递给EmployeeController中的create动作。

I've scoured other posts and nothing seems to be on point. 我搜寻了其他帖子,但似乎没有任何内容。 Any suggestions most appreciated! 任何建议,不胜感激!

Ok, the problem seems to be the nested attribute. 好的,问题似乎出在嵌套属性上。 Try to change in the EmployeesController#create the first row in: 尝试更改EmployeesController#create中的第一行:

@company = Company.find(params[:employee][:company_id])

EDIT 编辑

Alternatively, and probably more easy, you can also change the form hidden_field like this: 另外,也可能更容易,您也可以像这样更改hidden_​​field的形式:

hidden_field_tag(:company_id, @company.id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM