1

我有一個網站,我正在通過就業跟蹤用戶公司。我需要知道我做錯了什麼,因爲當我創建一個新的用戶公司時,用戶不知道它。Rails has_many:通過創建新的和在控制器中的鏈接

companies_controller.rb

class CompaniesController < ApplicationController 
    # GET /companies 
    # GET /companies.json 
    def index 
    @companies = current_user.companies 
    respond_to do |format| 
     format.html # index.html.erb 
     format.json { render json: @companies } 
    end 
    end 

    # GET /companies/1 
    # GET /companies/1.json 
    def show 
    @company = Company.find(params[:id]) 

    respond_to do |format| 
     format.html # show.html.erb 
     format.json { render json: @company } 
    end 
    end 

    # GET /companies/new 
    # GET /companies/new.json 
    def new 
    @company = Company.new 

    respond_to do |format| 
     format.html # new.html.erb 
     format.json { render json: @company } 
    end 
    end 

    # GET /companies/1/edit 
    def edit 
    @company = Company.find(params[:id]) 
    end 

    # POST /companies 
    # POST /companies.json 
    def create 
    @company = Company.new(params[:company]) 

    current_user.employments.create!(company_id: @company.id) 

    respond_to do |format| 
     if @company.save 
     format.html { redirect_to @company, notice: 'Company was successfully created.' } 
     format.json { render json: @company, status: :created, location: @company } 
     else 
     format.html { render action: "new" } 
     format.json { render json: @company.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    # PUT /companies/1 
    # PUT /companies/1.json 
    def update 
    @company = Company.find(params[:id]) 

    respond_to do |format| 
     if @company.update_attributes(params[:company]) 
     format.html { redirect_to @company, notice: 'Company was successfully updated.' } 
     format.json { head :no_content } 
     else 
     format.html { render action: "edit" } 
     format.json { render json: @company.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    # DELETE /companies/1 
    # DELETE /companies/1.json 
    def destroy 
    @company = Company.find(params[:id]) 
    @company.destroy 

    respond_to do |format| 
     format.html { redirect_to companies_url } 
     format.json { head :no_content } 
    end 
    end 
end 

回答

3

的問題是你創建的行動中,特別是

current_user.employments.create!(company_id: @company.id) 

之前被保存在公司的記錄,因此不會有一個id(這是執行的行==無)。只需在

if @company.save 

之後移動該行,它應該通過:through關係將其附加到current_user。

+0

謝謝!工作很好。 – Jaba 2012-07-10 05:31:08

相關問題