1

在我的 MechanicsController 中,创建操作有效,但是,当我检查数据库时,我注意到出租车永远不会获得 driver_id,我似乎永远无法让出租车同时包含 mechanic_id 和 driver_id而且我不确定我哪里出错了。

帮助将不胜感激...

class Driver < ActiveRecord::Base
  has_many :taxis
  has_many :mechanics, :through => :taxis
end


class Mechanic < ActiveRecord::Base
  has_many :driver, :through => :taxis
  has_many :taxis
end


class Taxi < ActiveRecord::Base
  belongs_to    :driver
  belongs_to :mechanic
end

class MechanicsController < ApplicationController
  def create

    this_driver=Driver.find(params[:driver_id])
    @mechanic = this_driver.mechanics.new(params[:mechanic])
    @taxi=@mechanic.taxis.new(params[:queueprocessor])

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

这是我的迁移:

class CreateDrivers < ActiveRecord::Migration
  def change
    create_table :drivers do |t|
      t.timestamps
    end
  end
end


class CreateMechanics < ActiveRecord::Migration
  def change
    create_table :mechanics do |t|
      t.timestamps
    end
  end
end

class Taxis < ActiveRecord::Migration
  def change
    create_table :taxis do |t|
      t.belongs_to :driver
      t.belongs_to :mechanic
      t.timestamps
    end
  end
end

谢谢

4

2 回答 2

3

这里有一些问题。改变这个:

class Mechanic < ActiveRecord::Base
  has_many :driver, :through => :taxis
  has_many :taxis
end

对此(注意:driver更改为:drivers):

class Mechanic < ActiveRecord::Base
  has_many :taxis
  has_many :drivers, :through => :taxis
end

此外,在create操作中,您以错误的顺序附加模型:

this_driver=Driver.find(params[:driver_id])
# this_driver.mechanics can't create a new association without a Taxi join model
@mechanic = this_driver.mechanics.new(params[:mechanic])   
@taxi=@mechanic.taxis.new(params[:queueprocessor])

应改为:

this_driver=Driver.find(params[:driver_id])
@taxi = this_driver.taxis.build(params[:queueprocessor])
@mechanic = @taxi.build_mechanic(params[:mechanic])
于 2013-05-23T14:51:07.040 回答
0

改变:

has_many :driver, :through => :taxis

至:

has_many :drivers, :through => :taxis
于 2013-05-23T14:27:18.680 回答