ruby-on-rails - ActiveRecord::StatementInvalid。 SQLite3::SQLException: 没有这样的表

标签 ruby-on-rails ruby ruby-on-rails-5 material-design-lite

我正在创建一个社交网络,但在添加“好友请求”时遇到了问题。 当我按下“添加 friend ”按钮时,Rails 控制台会显示以下内容。

Console error

迁移友谊:

class CreateFriendships < ActiveRecord::Migration[5.1]
  def change
    create_table :friendships do |t|
      t.references :user, foreign_key: true
      t.references :friend, foreign_key: true
      t.string :status

      t.timestamps
    end
  end
end

Controller :

class FriendshipsController < ApplicationController
    before_action :find_friend,except: [:index,:update]
    before_action :find_friendship, only: [:update]

    def create
        friendship = Friendship.new(user: current_user, friend: @friend)
        respond_to do |format|
            if friendship.save
                format.html { redirect_to @friend }
                format.js
            else
                format.html {redirect_to @friend, notice: "Error!"}
                format.js
            end
        end
    end 

    private     
    def find_friend
        @friend = User.find(params[:friend_id])
    end
end

模型友谊:

class Friendship < ApplicationRecord
  include AASM
  belongs_to :user
  belongs_to :friend, class_name: "User"
  validates :user_id, uniqueness:{scope: :friend_id} 

  aasm column: "status" do
    state :pending, initial: true
    state :active
    state :denied
    state :blocked
    event :accepted do
        transitions from: [:pending], to: [:active]
    end

    event :rejected do
        transitions from: [:pending, :active], to: [:denied]
    end

    event :eliminated do
        transitions from: [:pending, :active, :denied], to: [:blocked]
    end
  end
end

模型用户:

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable

  validates :rut, presence: true, uniqueness: true, rut: true
  validates :username, presence: true
  validates :name, presence: true
  validates :email, presence: true

  validate :validate_username_regex

  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :omniauthable,
         :omniauth_providers => [:facebook]


  has_many :posts
  has_many :friendships

  ...
  def self.from_omniauth(auth)
    where(provider: auth["provider"], uid: auth["uid"]).first_or_create do |user|
        if auth[:info]
            user.email = auth[:info][:email]
            user.name = auth[:info][:name]
        end
        user.password = Devise.friendly_token[0,20]
    end
  end
  ...
  private
    def validate_username_regex
      unless username =~ /\A[a-zA-Z]*[a-zA-Z][a-zA-Z0-9_]*\z/
        errors.add(:username,"XYZ...")
        errors.add(:username,"XXXYYYZZZ...")
      end
    end
end

添加好友按钮:

=grid xs:4,sm:2 do
    =button_to friendships_path(friend_id: @user.id),
     method: :post, remote: true, :"data-type" => "script",
     class:"mdl-button mdl-js-button mdl-button--fab 
     mdl-js-ripple-effect" do
        %i.material-icons person_add

架构:

  create_table "friendships", force: :cascade do |t|
    t.integer "user_id"
    t.integer "friend_id"
    t.string "status"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["friend_id"], name: "index_friendships_on_friend_id"
    t.index ["user_id"], name: "index_friendships_on_user_id"
  end

  create_table "posts", force: :cascade do |t|
    t.text "body"
    t.integer "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["user_id"], name: "index_posts_on_user_id"
  end

  create_table "users", force: :cascade do |t|
    t.string "email", default: "", null: false
    t.string "username", default: "", null: false
    t.string "name"
    t.string "last_name"
    t.string "rut", default: "", null: false
    t.string "bio"
    t.string "uid"
    ...
    end

end

rails : rails 5.1.6

ruby : ruby 2.3.1p112 (2016-04-26) [x86_64-linux-gnu]

有什么想法吗? :c 谢谢!

最佳答案

您需要更改此迁移。由于外键约束数据库正在尝试查找 ID 为 friend_id

friend 记录
class CreateFriendships < ActiveRecord::Migration[5.1]
  def change
    create_table :friendships do |t|
      t.references :user, foreign_key: true
      t.references :friend, foreign_key: true
      t.string :status

      t.timestamps
    end
  end
end

您需要从引用中删除foreign_key

t.references :friend, foreign_key: false

添加foreign_key手动

add_foreign_key :friendships, :users, column: :friend_id

迁移的最终内容

class CreateFriendships < ActiveRecord::Migration[5.1]
  def change
    create_table :friendships do |t|
      t.references :user, foreign_key: true

      t.references :friend, foreign_key: false
      # OR
      # t.integer :friend_id, index: true #=> Alternative to above line

      t.string :status

      t.timestamps
    end
    add_foreign_key :friendships, :users, column: :friend_id
  end
end

关于ruby-on-rails - ActiveRecord::StatementInvalid。 SQLite3::SQLException: 没有这样的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50614670/

相关文章:

ruby-on-rails - 将源关键字和搜索关键字与帐户创建相关联

javascript - 警告 : Error during font loading: Maximum call stack size exceeded error with PDFJS on rails

ruby-on-rails - 头像默认图片不显示

ruby - 使用 && ("and") 就像在 ruby 中一样?

ruby-on-rails - Rails 4 to_json 产生意外异常 nil 不是符号

jquery - GON - 在 js.erb + Rails 5 中没有获得值(value)

ruby-on-rails - Rails 嵌套事务

ruby-on-rails - Rails 3:缓存到全局变量

ruby - 为什么 SQLite3 中的 LIKE 在此语句中有效但 = 无效?

ruby-on-rails - Rails 5 - CanCan