rails has_many通过并在控制器中调用关联

时间:2013-05-23 14:14:05

标签: ruby-on-rails polymorphic-associations model-associations

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

非常感谢帮助...

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

谢谢

2 个答案:

答案 0 :(得分: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])

答案 1 :(得分:0)

变化:

has_many :driver, :through => :taxis

为:

has_many :drivers, :through => :taxis