对同一个表RoR的多个引用

时间:2018-01-02 16:27:45

标签: ruby-on-rails database model foreign-keys

我有两个模型,User和Peticion。我希望Peticion将两个引用保存到两个不同的用户,也就是说,两个用户的ID。这是创建Peticion模型的迁移

class CreatePeticionExtras < ActiveRecord::Migration[5.1]
  def change
    create_table :peticion_extras do |t|
      t.references :user_solicitante, foreign_key: true
      t.references :user_solicitado, foreign_key: true
      t.timestamps
    end
  end
end

Peticion的模特

class PeticionExtra < ActiveRecord::Base
  belongs_to :solicitante, class_name: "User"
  belongs_to :solicitado, class_name: "User"
end

用户的模型

class User < ActiveRecord::Base
  has_many :solicitudes, class_name: "PeticionExtra", foreign_key: "user_solicitado_id", dependent: :destroy
  has_many :peticiones, class_name: "PeticionExtra", foreign_key: "user_solicitante_id", dependent: :destroy

问题在于,当我在控制器上调用Peticion的创建时

def create
    peticion_extra = PeticionExtra.new(user_solicitante_id: params[:peticionextra][:user_solicitante_id], user_solicitado_id: params[:peticionextra][:user_solicitado_id])
respond_to do |format|
      if peticion_extra.save
        flash[:success] = "Petición enviada"
        format.html {redirect_to ejercicios_path and return}
        format.json {redirect_to ejercicios_url and return}
      else
        format.html {render action: "new"}
        format.json {render json: @user.errors, status: :unprocessable_entity}
      end
    end
  end

它会抛出一个错误:&#34; SQLite3 :: SQLException at / peticion_extra / crear 没有这样的表:main.user_solicitados&#34;在if peticion_extra.save

2 个答案:

答案 0 :(得分:0)

首先 - 你不能像你提议的那样有两个不同的关系:user

class PeticionExtra < ActiveRecord::Base
  belongs_to :user, class_name: "User", foreign_key: "user_solicitante_id"
  belongs_to :user, class_name: "User", foreign_key: "user_solicitado_id"
end

如果你做了

,请尝试回答一个问题
PetitionExtra.last.user

它应该返回solicitado还是solicitante

尝试:

class PeticionExtra < ActiveRecord::Base
  belongs_to :solicitante, class_name: "User"
  belongs_to :solicitado, class_name: "User"
end

我的代码中没有任何其他明显的问题......

答案 1 :(得分:0)

问题在于迁移。在我建立foreign_key: true时,它一直在寻找user_solicitante和user_solicitado表。我解决了这个改变迁移的问题:

class CreatePeticionExtras < ActiveRecord::Migration[5.1]
  def change
    create_table :peticion_extras do |t|
      t.references :user_solicitante, foreign_key: { to_table: :users }
      t.references :user_solicitado, foreign_key: { to_table: :users }
      t.timestamps
    end
  end
end