简体   繁体   中英

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

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 :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:

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"

Seems my view is failing to pass the :company_id on to the create action in the EmployeeController.

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:

@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_tag(:company_id, @company.id)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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