繁体   English   中英

[英]#<ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: users.sender_id:

我正在Rails应用程序中构建三个模型。 一个模型引用同一模型两次,如我的数据库模式所示。 唯一的问题是,当我发出POST请求以在货运表中创建新记录时。 我收到此错误:

 #<ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: users.sender_id: SELECT \\"users\\".* FROM \\"users\\" WHERE \\"users\\".\\"sender_id\\" = ? LIMIT ?> 

我认为不需要在用户表中添加sender_id和receiver_id列,因为sender_id和Receiver_id基本上是users列中的User_ID。 任何帮助将不胜感激!

这是我的user.rb文件:

 class User < ApplicationRecord has_many :shipments end 

这是我的shipment.rb

 class Shipment < ApplicationRecord belongs_to :sender, class_name: "User", primary_key: "sender_id" belongs_to :receiver, class_name: "User", primary_key: "receiver_id" validates_uniqueness_of :tntcode end 

这是我的shipss_controller:

 class ShipmentsController < ApplicationController def index shipments = Shipment.all end def show shipment = Shipment.find(params[:id]) end def create shipment = Shipment.new(shipment_params) if shipment.save render json: {status: 'Shipment created successfully'}, status: :created else render json: { errors: shipment.errors.full_messages }, status: :bad_request end end def shipment_params params.require(:shipment).permit(:tntcode, :status, :shipment_type, :weight, :content, :price, :sender_id, :receiver_id) end end 

而我的schema.rb:

 ActiveRecord::Schema.define(version: 20180826123320) do create_table "shipments", force: :cascade do |t| t.integer "tntcode" t.string "status" t.string "shipment_type" t.integer "weight" t.string "content" t.integer "price" t.integer "sender_id" t.integer "receiver_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["receiver_id"], name: "index_shipments_on_receiver_id" t.index ["sender_id"], name: "index_shipments_on_sender_id" end create_table "users", force: :cascade do |t| t.string "name" t.string "email", null: false t.string "role" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "photourl" t.string "userid" end end 

您不想更改您的belongs_to关联上的primary_key :这是另一个表的ID列( id )。

相反,您想要:

belongs_to :sender, class_name: "User", foreign_key: "sender_id"
belongs_to :receiver, class_name: "User", foreign_key: "receiver_id"

...这是默认设置,因此也应该起作用:

belongs_to :sender, class_name: "User"
belongs_to :receiver, class_name: "User"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM