首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >rails在控制器中通过has_many和调用关联

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

Stack Overflow用户
提问于 2013-05-23 22:14:05
回答 2查看 6.2K关注 0票数 1

在我的MechanicsController中,create操作起作用了,然而,当我检查数据库时,我注意到出租车从来没有得到driver_id,我似乎永远不能让出租车同时包含mechanic_id和driver_id,并且我不确定我错在哪里。

如果能帮上忙我会很感激的。

代码语言:javascript
复制
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

下面是我的迁移:

代码语言:javascript
复制
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

谢谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-05-23 22:51:07

这里有一些错误的地方。更改此设置:

代码语言:javascript
复制
class Mechanic < ActiveRecord::Base
  has_many :driver, :through => :taxis
  has_many :taxis
end

(请注意,:driver已更改为:drivers):

代码语言:javascript
复制
class Mechanic < ActiveRecord::Base
  has_many :taxis
  has_many :drivers, :through => :taxis
end

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

代码语言:javascript
复制
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])

应更改为:

代码语言:javascript
复制
this_driver=Driver.find(params[:driver_id])
@taxi = this_driver.taxis.build(params[:queueprocessor])
@mechanic = @taxi.build_mechanic(params[:mechanic])
票数 3
EN

Stack Overflow用户

发布于 2013-05-23 22:27:19

更改:

代码语言:javascript
复制
has_many :driver, :through => :taxis

至:

代码语言:javascript
复制
has_many :drivers, :through => :taxis
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16716272

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档