尝试将关联模型包含到JSON响应时Rails数据库错误

时间:2016-07-15 14:04:01

标签: ruby-on-rails json sqlite

我正在尝试使用Rails 4通过API构建消息传递系统。

型号:

class User < ActiveRecord::Base
 has_many :sent_messages, class_name: "Message", foreign_key: "sender_id"
 has_many :received_messages, class_name: "Message", foreign_key: "recipient_id"
end

class Message < ActiveRecord::Base
 belongs_to :sender, class_name: "User", primary_key: "sender_id"
 belongs_to :recipient, class_name: "User", primary_key: "recipient_id"
end

迁移

class DeviseTokenAuthCreateUsers < ActiveRecord::Migration
 def change
  create_table(:users) do |t|

   ...

   ## User Info
   t.string :name

   ...

  end
 end
end

class CreateMessages < ActiveRecord::Migration
 def change
  create_table :messages do |t|

    t.string :msg_body

    t.belongs_to :sender, class_name: "User", primary_key: "sender_id", index: true
    t.belongs_to :recipient, class_name: "User", primary_key: "recipient_id", index: true
    t.timestamps null: false
  end
 end
end

消息控制器:

class MessagesController < ApplicationController

 def index
  messages = Message.all
  render :json => messages.as_json(:include => [:sender, :recipient])
 end

end

问题

问题是,当我收到所有消息的GET请求时,我收到此错误:

ActiveRecord::StatementInvalid (SQLite3::SQLException: no such column: users.sender_id: SELECT  "users".* FROM "users" WHERE "users"."sender_id" = ? LIMIT 1)

那么,我做错了什么?为什么?我该怎么办?

0 个答案:

没有答案